我遇到了以下
Plunker来动态添加和删除组件.
根据以上链接和许多其他SO帖子,我知道如何访问输入和输出属性:
根据以上链接和许多其他SO帖子,我知道如何访问输入和输出属性:
this.compRef.instance.someProperty = 'someValue'; this.compRef.instance.someOutput.subscribe(val => doSomething());
而且我还有一个指令“appFont”.
import { Directive,ElementRef } from '@angular/core'; @Directive({ selector: '[appFont]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.font = 'Calibri'; } }
如何将这个“appFont”指令添加到新动态创建的组件中?
解决方法
这可能应该做的工作.你可以从@Input()中获取一些HTML元素,或者只是通过getElement(s)来定位元素.然后你将属性添加到组件中.
@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") } }