Angular如何自定义attribute指令

需求:
实现一个自定义的attribute directive,当施加到某个html element时,鼠标hover上去,会修改其背景颜色。

Highlight me!

下面是具体做法。

(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

element into the directive's constructor which sets the

element's background style to yellow.

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

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

posted @ 2020-08-29 13:23  JerryWang_汪子熙  阅读(210)  评论(0编辑  收藏  举报