Attaching directives to dynamically added elements

2020-07-18 07:26发布

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?

标签: angular
2条回答
太酷不给撩
2楼-- · 2020-07-18 08:02

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.

查看更多
Lonely孤独者°
3楼-- · 2020-07-18 08:06

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

查看更多
登录 后发表回答