Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching directives to dynamically added elements

Tags:

angular

When you add an element with a directive to the DOM using another element's ElementRef.nativeElement.innerHTML property, the directive does not fire. How do I add an element to the DOM in a way that causes the directive to fire?

Example
If in my component I do something like the following:

export class AppComponent implements OnInit {

    constructor(private _elem: ElementRef) { }    

    ngOnInit() {
        this._elem.nativeElement.innerHTML = '<span myDirective>Foo</span>';
    }

}

(This is a major simplification over my actual implementation, so let's ignore that this is bad practice for a second)

Then the myDirective that appears to be attached to the <span> will never actually run.

The question is: how do I get angular to recognize the new element with the directive so that it runs?

like image 520
otoomey Avatar asked Oct 17 '22 08:10

otoomey


2 Answers

On the fly compilation is removed from Angular 2+. Another Alternative loading components dynamically using Dynamic Component Loader. For this you have to change your existing implementation

https://angular.io/guide/dynamic-component-loader

like image 163
Jameel Moideen Avatar answered Nov 15 '22 08:11

Jameel Moideen


If you are nesting components inside each other, you need to look at:

  • Content Projection and <ng-content>
  • @ContentChild
  • @ContentChildren
  • QueryList.

Joshua Morony also did an Ionic youtube video - covering these Angular features.

like image 29
JGFMK Avatar answered Nov 15 '22 10:11

JGFMK