问题
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")
}
}
来源:https://stackoverflow.com/questions/49365011/angular-2-add-directive-to-dynamically-created-components