應用繼續演進。 首先加入的是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,
],