angular5中的自定义指令(属性指令)

属性型指令用于改变一个 DOM 元素的外观或行为。api

在 Angular 中有三种类型的指令:app

  1. 组件 — 拥有模板的指令ide

  2. 结构型指令 — 经过添加和移除 DOM 元素改变 DOM 布局的指令函数

  3. 属性型指令 — 改变元素、组件或其它指令的外观和行为的指令。布局

在cmd的命令窗口里面执行命令:ng generate directive highlightui

生成的 src/app/highlight.directive.ts 文件以下:this

import { Directive } from '@angular/core';

@Directive({ selector: '[appHighlight]' })

export class HighlightDirective {

constructor() { } 
}

 

import 语句还从 Angular 的 core 库中导入了一个 ElementRef 符号。spa

你能够在指令的构造函数中注入 ElementRef,来引用宿主 DOM 元素,code

ElementRef 经过其 nativeElement 属性给你了直接访问宿主 DOM 元素的能力。blog

 

使用方法:

<p appHighlight>Highlight me!</p>

总结:Angular 在宿主元素 <p> 上发现了一个 appHighlight 属性。 而后它建立了一个 HighlightDirective 类的实例,并把所在元素的引用注入到了指令的构造函数中。 在构造函数中,该指令把 <p> 元素的背景设置为了黄色。 

响应用户引起的事件

先把 HostListener 加进导入列表中。

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

而后使用 HostListener 装饰器添加两个事件处理器,它们会在鼠标进入或离开时进行响应。

@HostListener('mouseenter') onMouseEnter() {
  this.highlight('yellow');
}

@HostListener('mouseleave') onMouseLeave() {
  this.highlight(null);
}

private highlight(color: string) {
  this.el.nativeElement.style.backgroundColor = color;
}

 

src/app/highlight.directive.ts 文件以下:

import { Directive, ElementRef, HostListener } from '@angular/core';
 
@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }
 
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }
 
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }
 
  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }

 Ps:这个demo的小例子是按照官网来的,是一个很经典的教程,为了偷懒,因此直接复制过来了。但愿老司机们不要喷。谢谢

可是这样写的话太死板了,不够灵活。。。好比说:我想鼠标通过不一样的div元素的时候,实现不一样的背景颜色,那这个时候就要用到数据绑定向指令传值了(@Input);

直接把最终的代码贴上来吧(运行下面的代码能够试试)

 src/app/highlight.directive.ts 文件以下:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) {
  }

  @Input() appHighlight: string;

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.appHighlight || 'red');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

使用的方法是:

<div> <input type="radio" name="colors" (click)="color='lightgreen'">Green <input type="radio" name="colors" (click)="color='yellow'">Yellow <input type="radio" name="colors" (click)="color='cyan'">Cyan </div> <p [appHighlight]="color">Highlight me!</p>
相关文章
相关标签/搜索