需要:
实现一个自定义的attribute directive,当施加到某个html element时,鼠标hover下来,会批改其背景色彩。

<p appHighlight>Highlight me!</p>

上面是具体做法。

(1) 应用命令行创立directive:

ng generate directive highlight

主动生成的文件:


import { Directive } from '@angular/core';@Directive({  selector: '[appHighlight]'})export class HighlightDirective {  constructor() { }}

中括号语法标注了这是一个attribute指令。Angular在解决模板里的html元素时,如果发现某个元素具备appHighlight属性,就会将该指令的行为施加给该元素。

这里的selector之所以不取名为highlight,是为了防止和html规范的属性抵触。同样,不应用ng作为前缀,为了防止和Angular预置的attribute指令抵触。应用app代表这是利用开发人员自定义的attribute指令。

指令的具体实现放在highlight.directive.ts里:

通过结构函数参数注入形式,将被施加attribute指令的DOM元素注入,这样指令能够通过nativeElement操作该DOM元素。

(2) 在html里生产该指令:

最初的成果:

It created an instance of the HighlightDirective class and injected a reference to the <p> element into the directive's constructor which sets the <p> element's background style to yellow.

在运行时,Angular找到模板里标注了appHighlight指令的element后,创立一个HighlightDirective class的实例,将这个element注入到directive实例的构造函数里。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":