1. 指令:
在 Angular 中有三種類型的指令:
組件 — 擁有模板的指令。
結構型指令 — 通過添加和移除 DOM 元素改變 DOM 布局的指令。
屬性型指令 — 改變元素、組件或其它指令的外觀和行為的指令。
組件是這三種指令中最常用的。
結構型指令修改視圖的結構。例如,NgFor
、NgIf
、NgSwitch
。要了解更多,參見結構型指令 。
屬性型指令改變一個元素的外觀或行為。例如,內置的 NgStyle
指令可以同時修改元素的多個樣式。
2. 宿主元素(host element)
了解指令前,我們需要先理解宿主元素。對于指令來說,這個概念是相當簡單的。應用指令的元素,就是宿主元素。如下文綁定自定義結構型指令的P
標簽就是宿主元素。
3. 自定義結構型指令
- 創建指令
composition.directive.ts
import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
@Directive({
selector: '[appComposition]'
})
export class CompositionDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) { }
@Input()
set appComposition (c: boolean) {
if (!c) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
- 使用指令
- 在組件所屬模塊
declarations
中導入
declarations: [
AppComponent,
CompositionDirective
],
- 模板中使用
<p *appComposition="false">當appComposition為false時出現這段話</p>
or
<ng-template [appComposition]="false">
<p>當appComposition為false時出現這段話</p>
</ng-template>
- 注意:
a. 我們可以使用TemplateRef
取得宿主元素的內容,并通過ViewContainerRef
來訪問這個視圖容器。
b. 使用@Input()
,通過setter
截聽輸入屬性值的變化,設置內嵌視圖。
c. 當appComposition
為false
,調用ViewContainerRef
類實例的createEmbeddedView
方法創建內嵌視圖
4. 自定義屬性指令
- 創建指令
height-light.directive.ts
import {Directive, ElementRef, HostListener, Input} from '@angular/core';
@Directive({
selector: '[appHeightLight]'
})
export class HeightLightDirective {
public default = 'yellow'
@Input('appHeightLight') light: string
constructor(
private el: ElementRef,
private ren: Renderer2
) { }
@HostListener('mouseenter') onMouseEnter () {
console.log(this.el)
this.el.nativeElement.style.backgroundColor = this.light;
this.ren.setStyle(this.el.nativeElement, 'fontSize', '20px');
}
@HostListener('mouseleave') onMouseLeave () {
this.el.nativeElement.style.backgroundColor = this.default;
}
}
- 使用指令
- 在組件所屬模塊
declarations
中導入
declarations: [
AppComponent,
HeightLightDirective
],
- 模板中使用
<p [appHeightLight]="'blue'">Highlighted in blue</p>
or
<p appHeightLight="orange">Highlighted in orange</p>
-
注意:
a.HostListener
是屬性裝飾器,用來為宿主元素添加事件監聽。
b.HostBinding
是屬性裝飾器,用來動態設置宿主元素的屬性值。
c. Angular 會為每個匹配的元素創建一個指令控制器類的實例,并把 Angular 的ElementRef
和Renderer
注入進構造函數。ElementRef
是一個服務,它賦予我們通過它的nativeElement
屬性直接訪問 DOM 元素的能力。Renderer
服務允許通過代碼設置元素的樣式。