Angular4 自定义指令

1. 创建指令文件

ng generate directive highlight

2.在highlight.directive.ts 中加入自定义样式(使用 HostListener 装饰器添加两个事件处理器,它们会在鼠标进入或离开时进行响应)

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

@Directive({

  selector: '[appHighlight]'

})

export class HighlightDirective {

@Input('appHighlight')  highlightColor: string;  //highlightColor是appHighlight指令的别名

  constructor(private el: ElementRef) {

  //  el.nativeElement.style.backgroundColor = 'yellow';

  }

  private highlight(color: string) {

    this.el.nativeElement.style.backgroundColor = color;

  }

  @HostListener('mouseenter') onMouseEnter() {

    this.highlight(this.highlightColor);

  }

  @HostListener('mouseleave') onMouseLeave() {

    this.highlight(null);

  }

}


3.在app.module.ts 中引入指令文件

import { HighlightDirective } from './highlight.directive';

declarations:[ HighlightDirective ]

4.在app.component.html 中应用指令

<p appHighlight>Highlight me!</p>  // 直接应用

5.运行本应用并确认:当把鼠标移到 p 上的时候,背景色就出现了,而移开的时候,它消失了

使用 @Input 数据绑定向指令传递值

6.在app.component.ts中定义属性

color = 'yellow';

7. 在app.component.html 中应用指令

 <p [appHighlight]="color" > Highlight me!</p>  

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容