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?
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
If you are nesting components inside each other, you need to look at:
<ng-content>
Joshua Morony also did an Ionic youtube video - covering these Angular features.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With