angular2.0定義指令

應用繼續演進。 首先加入的是HighlightDirective,一個屬性型指令,它會設置所在元素的背景色。

app/highlight.directive.ts

import { Directive, ElementRef, Renderer } from '@angular/core';

@Directive({ selector: '[highlight]' })
/** Highlight the attached element in gold */
export class HighlightDirective {
  constructor(renderer: Renderer, el: ElementRef) {
    renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'gold');
    console.log(
      `* AppRoot highlight called for ${el.nativeElement.tagName}`);
  }
}

我們更新AppComponent的模板,來把該指令附加到標題上:

template: '<h1 highlight>{{title}}</h1>'

如果我們現在就運行該應用,Angular 將無法識別highlight屬性,並且忽略它。 我們必須在AppModule中聲明該指令。

導入HighlightDirective類,並把它加入該模塊的declarations數組中,就像這樣:

declarations: [
  AppComponent,
  HighlightDirective,
],
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章