一、定义
为 Angular 应用程序模板中的标签添加额外行为的类。
二、分类
内置指令
- 属性型指令:
NgClass、 NgStyle、 NgModel - 结构型指令:
NgIf、 NgFor、 NgSwitch
自定义指令
自定义属性型指令
创建及使用
1.在directives文件目录创建highlight指令
ng g d directives/highlight
创建的highlight.directive.ts文件如下
import { Directive } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor() { }
}
2.从 @angular/core导入ElementRef,ElementRef的nativeElement属性会提供对宿主 DOM 元素的直接访问权限 3.在指令的 constructor() 中添加ElementRef 以注入对宿主DOM 元素的引用,该元素就是 appHighlight 的作用目标 4.从 @angular/core导入OnInit并实现其生命周期函数,在ngOnInit添加逻辑。
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
constructor(private el: ElementRef) { }
ngOnInit() {
this.el.nativeElement.style.color = 'red';
}
}
5.指令的使用 被appHighlight标记的元素的文本将显示为红色
<div appHighlight>指令的使用说明</div>
传递参数
import { Directive, ElementRef, OnInit, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
@Input() appHighlight: string = '';
constructor(private el: ElementRef) { }
ngOnInit() {
this.el.nativeElement.style.color = this.appHighlight;
}
}
<div appHighlight="blue">指令的使用说明</div>
处理事件
import { Directive, ElementRef, OnInit, Input, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
@Input() appHighlight: string = '';
@HostListener('mouseover') onMouseOver() {
this.setColor(this.appHighlight);
}
@HostListener('mouseout') onMouseOut() {
this.setColor('');
}
constructor(private el: ElementRef) { }
ngOnInit() {
this.el.nativeElement.style.color = this.appHighlight;
}
setColor(color: string) {
this.el.nativeElement.style.color = color;
}
}
|