应用继续演进。 首先加入的是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,
],