如何在 Angular 5 中的指令上使用 exportAs 以在模板中获取其引用? [英] How to use exportAs in Angular 5 on directives to get its reference in the template?
问题描述
我有以下指令:
@Directive({选择器: '[changeColor]',exportAs:'changeColor'})导出类 ColorDirective {构造函数(元素:ElementRef,渲染器:Renderer2){renderer.setStyle(elem.nativeElement, 'color', 'red');}}
我有以下模板:
你好
这按预期工作,并以红色显示你好".但是,当我尝试访问指令的引用时,出现错误.例如,下面的代码:
你好
{{X}}
产生以下错误没有将exportAs"设置为changeColor"的指令
.我哪里出错了?
您没有在第二个代码段中应用 changeColor
指令,因为没有 changeColor
属性在 h1
上.应该是
你好
<块引用>
你能解释为什么一个属性的选择器应该在[]内
因为这是 CSS 选择器的语法(与您在 CSS 样式表中使用的相同):
[foo]
选择具有名为 foo 的属性的任何元素.foo
选择具有名为 foo 的 CSS 类的任何元素foo
选择任何名为 foo 的元素bar[foo]:not(.baz)
选择任何名为 bar 的元素,该元素具有名为 foo 的属性,但没有名为 baz 的类.
I have the below directive:
@Directive({
selector: '[changeColor]',
exportAs:'changeColor'
})
export class ColorDirective {
constructor(elem: ElementRef, renderer: Renderer2) {
renderer.setStyle(elem.nativeElement, 'color', 'red');
}
}
I have the below template:
<h1 changeColor>Hello</h1>
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}}
produces the below error "There is no directive with "exportAs" set to "changeColor""
. Where am I going wrong?
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 [ ]
Because that's the syntax for CSS selectors (the same you're using in a CSS stylesheet):
[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屋!