簡體   English   中英

如何在指令的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”。 但是,當我嘗試訪問指令的引用時,出現錯誤。 例如,下面的代碼:

<h1 #x=changeColor>Hello</h1>
{{x}}

產生以下錯誤"There is no directive with "exportAs" set to "changeColor"" 我要去哪里錯了?

您沒有在第二個代碼段中應用changeColor指令,因為h1上沒有changeColor屬性。 它應該是

<h1 changeColor #x="changeColor">Hello</h1>

你能解釋為什么一個屬性的選擇器應該在[]內嗎

因為這是CSS選擇器的語法(與CSS樣式表中使用的語法相同):

  • [foo]選擇具有名為foo的屬性的任何元素
  • .foo選擇具有CSS類foo的任何元素
  • foo選擇任何名為foo的元素
  • bar[foo]:not(.baz)選擇任何名為bar的元素,該元素具有名為foo的屬性,並且沒有名為baz的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM