angular自定义指令 directive

在命令行窗口下用 CLI 命令 ng generate directive 在app/directivess文件夹下创建指令类文件。

ng generate directive directives/highlight

可也一自己手动新建文件,highlight.directive.ts

app/directives/highlight.directive.ts的内容如下:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]' // 指令名称
})
export class HighlightDirective {
  el:ElementRef
    constructor(el: ElementRef) {
       this.el = el;
    }
    @Input('appHighlight') highlightColor: string; // 传进来的颜色

    @HostListener('mouseenter') onMouseEnter() { // 绑定事件
       this.highlight(this.highlightColor || 'red');
    }
    
    @HostListener('mouseleave') onMouseLeave() {
      this.highlight(null);
    }
    
    private highlight(color: string) {
      this.el.nativeElement.style.backgroundColor = color;
    }
}

在app.module.ts中

@NgModule({
  declarations: [
    ...
    HighlightDirective,
    ...
  ],
  ...
})

使用:
<p [appHighlight]="'pink'">Highlight me!</p>  // 粉色
<p appHighlight>Highlight me!</p> // 红色

参考文献:angular官网-directive

发布了112 篇原创文章 · 获赞 149 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/l284969634/article/details/102657064