如何在 Angular 5 on 指令中使用 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>
can you explain why the selector of an attribute should be within [ ]
因为这是 CSS 选择器的语法(与您在 CSS 样式表中使用的语法相同):
[foo]
选择具有名为 foo 的属性的任何元素
.foo
选择任何具有 CSS class 名为 foo 的元素
foo
选择任何名为 foo 的元素
bar[foo]:not(.baz)
选择任何名为 bar 的元素,该元素具有名为 foo 的属性并且没有 class 名为 baz.
我有以下指令:
@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>
can you explain why the selector of an attribute should be within [ ]
因为这是 CSS 选择器的语法(与您在 CSS 样式表中使用的语法相同):
[foo]
选择具有名为 foo 的属性的任何元素
.foo
选择任何具有 CSS class 名为 foo 的元素
foo
选择任何名为 foo 的元素
bar[foo]:not(.baz)
选择任何名为 bar 的元素,该元素具有名为 foo 的属性并且没有 class 名为 baz.