![](/img/trans.png)
[英]angular - how to get a reference of a directive which has no exportAs
[英]How to use exportAs in Angular 5 on directives to get its reference in the template?
我有以下指令:
@Directive({
selector: '[changeColor]',
exportAs:'changeColor'
})
export class ColorDirective {
constructor(elem: ElementRef, renderer: Renderer2) {
renderer.setStyle(elem.nativeElement, 'color', 'red');
}
}
我有以下模板:
<h1 changeColor>Hello</h1>
这将按预期方式工作,并以红色显示“ Hello”。 但是,当我尝试访问指令的引用时,出现错误。 例如,下面的代码:
<h1 #x=changeColor>Hello</h1>
{{x}}
产生以下错误"There is no directive with "exportAs" set to "changeColor""
。 我要去哪里错了?
您没有在第二个代码段中应用changeColor
指令,因为h1
上没有changeColor
属性。 它应该是
<h1 changeColor #x="changeColor">Hello</h1>
你能解释为什么一个属性的选择器应该在[]内吗
因为这是CSS选择器的语法(与CSS样式表中使用的语法相同):
[foo]
选择具有名为foo的属性的任何元素 .foo
选择具有CSS类foo的任何元素 foo
选择任何名为foo的元素 bar[foo]:not(.baz)
选择任何名为bar的元素,该元素具有名为foo的属性,并且没有名为baz的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.