环境:
- Angular CLI: 11.0.6
- Angular: 11.0.7
- Node: 12.18.3
- npm : 6.14.6
- IDE: Visual Studio Code
指令(Directive)在Angular 1.0时代(当时叫AngularJS)是很流行的,现在用到的偏少。可以简单理解为,指令(Directive)用于扩展已有Element(DOM)。
如果去看Angular源码,可以看到下面定义
/**
* Supplies configuration metadata for an Angular component.
*
* @publicApi
*/
export declare interface Component extends Directive {
是的,Component派生于Directive,也就是说,Component属于Directive。
*ngFor
、*ngIf
和 *ngSwitch
。由于结构型指令会修改 DOM 结构,因而同一个 HTML 标签上面不能同时使用多个结构型指令。如果要在同一个 HTML 元素上面使用多个结构性指令,可以考虑加一层空的元素来嵌套,比如在外面套一层空的(div
) 。Angualr中用指令来增强DOM的功能,包括 HTML 原生DOM和我们自己自定义的组件(Component)。举例来说,可以扩展一个Button,实现避免点击后,服务器端未响应前的二次点击;高亮某些收入内容等等。
实现一个指令,鼠标移动到上面时, 背景显示为黄色,鼠标移开,恢复正常。
ng generate directive MyHighlight
Anuglar CLI自动生成html、css、ut等文件。
import { Directive, ElementRef } from ‘@angular/core‘;
@Directive({
selector: ‘[appHighlight]‘
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = ‘yellow‘;
}
@HostListener(‘mouseenter‘) onMouseEnter() {
this.highlight(‘yellow‘);
}
@HostListener(‘mouseleave‘) onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
<p my-highlight>Highlight me!</p>
my-highlight
即我们的元素扩展属性(指令、directive)。
*ngFor
、*ngIf
和 *ngSwitch
都是Angular内置的指令。---------------- END ----------------
======================
Angular入门到精通系列教程(10)- 指令(Directive)
原文:https://www.cnblogs.com/skywind/p/14272393.html