如何在指令的Angular 5中使用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".但是,当我尝试访问指令的引用时,出现错误.例如,下面的代码:
This works as expected and displays "Hello" in red. But, when I try to access a reference of the directive I get an error. For example, the below code:
<h1 #x=changeColor>Hello</h1>
{{x}}
产生以下错误"There is no directive with "exportAs" set to "changeColor""
.我要去哪里错了?
produces the below error "There is no directive with "exportAs" set to "changeColor""
. Where am I going wrong?
推荐答案
您没有在第二个片段中应用changeColor
指令,因为h1
上没有changeColor
属性.应该是
You didn't apply the changeColor
directive in the second snippet, since there is no changeColor
attribute on the h1
. It should be
<h1 changeColor #x="changeColor">Hello</h1>
您能解释一下为什么属性选择器应该在[]内吗?
can you explain why the selector of an attribute should be within [ ]
因为这是CSS选择器的语法(与CSS样式表中使用的语法相同):
Because that's the syntax for CSS selectors (the same you're using in a CSS stylesheet):
-
[foo]
选择任何具有名为foo的属性的元素 -
.foo
选择CSS类名为foo 的任何元素
-
foo
选择任何名为foo的元素 -
bar[foo]:not(.baz)
选择任何名为bar的元素,该元素具有名为foo的属性,并且没有名为baz的类.
[foo]
selects any element with an attribute named foo.foo
selects any element with a CSS class named foofoo
selects any element named foobar[foo]:not(.baz)
selects any element named bar, which has an attribute named foo and doesn't have a class named baz.
这篇关于如何在指令的Angular 5中使用exportAs在模板中获取其引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!