Home Angular4 not processing selectors for components/directives for dom elements inserted dynamically
Reply: 0

Angular4 not processing selectors for components/directives for dom elements inserted dynamically

Suresh Nagar
1#
Suresh Nagar Published in 2018-02-14 01:36:08Z

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';
    }
}

https://plnkr.co/edit/PXiXgqYic4qsUYsDfWKk?p=preview

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32131 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO