[英]Angular 2: Add directive to dynamically created component(s)
我遇到了以下Plunker来动态添加和删除组件。 根据上面的链接和许多其他 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”指令添加到新的动态创建的组件中?
如果您可以手动获取构造函数所需的东西,您可以简单地执行以下操作:
const highlight = new HighlightDirective(...);
❗ 请注意,这不是标准的 Angular 代码。 让 Angular 为您完成工作几乎总是更可取的,因为您可能会不小心逃脱它的管道并变得无赖。 如果发生这种情况,你可能会遇到意想不到的 Angular 行为,因为 Angular 不知道你在做什么......
一个 3 年前的问题......我想知道是否有人仍在努力实现这一目标。
这可能应该做的工作。 你可以从@Input()
获取一些HTML元素,或者只是通过getElement(s)By..
来定位你的元素。 然后将属性添加到组件。
@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")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.