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

末鹿安然 提交于 2019-12-11 06:36:49

问题


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?


回答1:


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 foo
  • foo selects any element named foo
  • bar[foo]:not(.baz) selects any element named bar, which has an attribute named foo and doesn't have a class named baz.


来源:https://stackoverflow.com/questions/49746274/how-to-use-exportas-in-angular-5-on-directives-to-get-its-reference-in-the-templ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!