本文介绍了Angular 2:向动态创建的组件添加指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了以下柱塞,以动态添加和删除组件.根据上面的链接以及其他许多SO帖子,我知道如何访问Input和Output属性:
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());
我还有一个指令"appFont".
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';
}
}
如何将此"appFont"指令添加到新动态创建的组件中?
How do I add this "appFont" directive to the new dynamically created component?
推荐答案
这应该可以完成工作.您可以从@Input()
获取一些HTML元素,或者仅通过getElement(s)By..
定位您的元素.然后将属性添加到组件.
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")
}
}
这篇关于Angular 2:向动态创建的组件添加指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!