How can we inject a attribute directive to the DOM element ( from ts file ) in angular

Viewed 674

Is it possible to add a directive to DOM element using setAttribute()?

I was trying to implement drag and drop in my component with material drag and drop. it is working, when i tried like this

<div class="example-boundary">
<div class="example-box" #test cdkDragBoundary=".example-boundary" cdkDrag>
    I can only be dragged within the dotted container
</div>

from my understanding, drag functionality work through cdkDrag attribute directive.

When i tried to add this directive through setAttribute(), which is not working

constructor(private _renderer: Renderer2, private _elRef: ElementRef) {}

ngAfterViewInit(): void {
   let requiredElem = this._elRef.nativeElement.querySelectorAll('.example-box');
   this._renderer.setAttribute(requiredElem[0], 'cdkDrag', '');
}

When i checking the DOM, seems cdkDrag is added. enter image description here

have any one to help me to sort this out? thanks in advance.

Edit

I have implemeted that drag functionality in iframe element using jquery (https://stackblitz.com/edit/angular-ivy-syoi3w?file=src/app/iframe/iframe.component.ts) this slackBlitz example facing an issue with jqueryUi lib.

1 Answers

The simple answer is no, you can't do this in Angular. What you're looking for was possible in the old angular.js, by using the $compile service. For eg:

element.setAttribute('cdkDrag', '');
$compile(element)($scope);

But, for a number of good reasons, the Angular team decided to drop support for such dynamic approaches in the new framework.

In the first few RC versions of Angular, there were some workarounds/hacks based on DynamicComponentLoader that would allow one to achieve a dynamic directive compilation on DOM elements, but later DynamicComponentLoader was also deprecated and then removed.

Related