5

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?

otoomey
  • 939
  • 1
  • 14
  • 31
  • 1
    I have tried to do that before without success, it seems we do not have this possibility yet, but at least you can see a related answer here: https://stackoverflow.com/questions/41298168/how-to-dynamically-add-a-directive. Hope it helps! – pinkfloyd Jul 26 '17 at 21:54
  • 2
    You need to compile it. Read [Here is what you need to know about dynamic components in Angular](https://hackernoon.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e) – Max Koretskyi Jul 27 '17 at 04:35
  • 1
    @Maximus thanks for the link. Much more useful and informative than the docs. – otoomey Jul 27 '17 at 09:00
  • 1
    @Campbell, you're welcome. If you find something unclear, you can post a clarification question here and I'll answer – Max Koretskyi Jul 27 '17 at 09:34

2 Answers2

2

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

Jameel Moideen
  • 7,542
  • 12
  • 51
  • 79
1

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

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

JGFMK
  • 8,425
  • 4
  • 58
  • 92