0

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

Suresh Nagar
  • 1,021
  • 9
  • 20
  • You can inject components into specific locations – Michael Kang Feb 14 '18 at 02:38
  • can you be more specific please? – Suresh Nagar Feb 14 '18 at 02:39
  • any of these you're after? https://stackoverflow.com/questions/34784778/equivalent-of-compile-in-angular-2 – Michael Kang Feb 14 '18 at 02:42
  • with the click of a button, for example, you could instantiate a component and inject it into a location using its ComponentFactoryResolver. If you're looking for a way to dynamically compile a string and process its directives, that's a lot harder, especially with AOT. – Michael Kang Feb 14 '18 at 02:43
  • i think, thats like on angular1, to need to 'compile' your can, that angular know he need to do something. This way you working outside of angular controlled environment. – moohkooh Feb 14 '18 at 02:58

0 Answers0