Angular 2: Add directive to dynamically created co

2019-06-19 02:40发布

问题:

I came across the following Plunker to dynamically add and remove components. According to the above link and from many other SO posts, I know how to access Input and Output properties:

this.compRef.instance.someProperty = 'someValue';
this.compRef.instance.someOutput.subscribe(val => doSomething()); 

And I also have a directive "appFont".

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appFont]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.font = 'Calibri';
    }
}

How do I add this "appFont" directive to the new dynamically created component?

回答1:

This should probably do the work. You can get some HTML element from @Input() or simply target your element by getElement(s)By... Then you add attribute to component.

@Component({
  selector: 'my-app',
  template: `<h1 id="header">{{title}}</h1>`
})
class AppComponent implements OnInit{
  @Input() el: ElementRef // or HTMLElement;
  title="hello world angular";

  ngOnInit() {
       el.nativeElement.createAttribute("appFont");
       // or 
       document.getElementById("header").createAttribute("appFont")
  }
}