简体   繁体   English

如何在指令的Angular 5中使用exportAs在模板中获取其引用?

[英]How to use exportAs in Angular 5 on directives to get its reference in the template?

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. 这将按预期方式工作,并以红色显示“ Hello”。 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"" . 产生以下错误"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 . 您没有在第二个代码段中应用changeColor指令,因为h1上没有changeColor属性。 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): 因为这是CSS选择器的语法(与CSS样式表中使用的语法相同):

  • [foo] selects any element with an attribute named foo [foo]选择具有名为foo的属性的任何元素
  • .foo selects any element with a CSS class named foo .foo选择具有CSS类foo的任何元素
  • foo selects any element named foo foo选择任何名为foo的元素
  • bar[foo]:not(.baz) selects any element named bar, which has an attribute named foo and doesn't have a class named baz. bar[foo]:not(.baz)选择任何名为bar的元素,该元素具有名为foo的属性,并且没有名为baz的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM