Attaching directives to dynamically added elements

Viewed 6056

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?

2 Answers
Related