关于angular:Angular如何自定义attribute指令

4次阅读

共计 906 个字符,预计需要花费 3 分钟才能阅读完成。

需要:
实现一个自定义的 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 的原创文章,请关注公众号 ” 汪子熙 ”:

正文完
 0