Why angular4 is not applying components/directives/bindings on the dynamically created dom elements.
I have a directive which is having a selector as 'span' so it applies to all the spans in the application. But if a span is inserted dynamically in the dom, the directive is not applied. How to make it working?
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<span>Testing</span>
<div id="dynamic">
</div>
`,
})
export class App implements AfterViewInit {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`;
}
ngAfterViewInit(){
const elem = document.getElementById('dynamic');
elem.innerHTML = '<span>Span inserted on the fly!!!</span>';
}
}
@Directive({
selector: 'span'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}