1. 指令:
在 Angular 中有三種類型的指令:
組件 — 擁有模板的指令付呕。
結(jié)構(gòu)型指令 — 通過添加和移除 DOM 元素改變 DOM 布局的指令媒峡。
屬性型指令 — 改變?cè)厮杳薄⒔M件或其它指令的外觀和行為的指令舞蔽。
組件是這三種指令中最常用的缸棵。
結(jié)構(gòu)型指令修改視圖的結(jié)構(gòu)。例如柿冲,NgFor
茬高、NgIf
、NgSwitch
假抄。要了解更多雅采,參見結(jié)構(gòu)型指令 。
屬性型指令改變一個(gè)元素的外觀或行為慨亲。例如婚瓜,內(nèi)置的 NgStyle
指令可以同時(shí)修改元素的多個(gè)樣式。
2. 宿主元素(host element)
了解指令前刑棵,我們需要先理解宿主元素巴刻。對(duì)于指令來說,這個(gè)概念是相當(dāng)簡單的蛉签。應(yīng)用指令的元素胡陪,就是宿主元素。如下文綁定自定義結(jié)構(gòu)型指令的P
標(biāo)簽就是宿主元素碍舍。
3. 自定義結(jié)構(gòu)型指令
- 創(chuàng)建指令
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
中導(dǎo)入
declarations: [
AppComponent,
CompositionDirective
],
- 模板中使用
<p *appComposition="false">當(dāng)appComposition為false時(shí)出現(xiàn)這段話</p>
or
<ng-template [appComposition]="false">
<p>當(dāng)appComposition為false時(shí)出現(xiàn)這段話</p>
</ng-template>
- 注意:
a. 我們可以使用TemplateRef
取得宿主元素的內(nèi)容柠座,并通過ViewContainerRef
來訪問這個(gè)視圖容器。
b. 使用@Input()
片橡,通過setter
截聽輸入屬性值的變化妈经,設(shè)置內(nèi)嵌視圖。
c. 當(dāng)appComposition
為false
,調(diào)用ViewContainerRef
類實(shí)例的createEmbeddedView
方法創(chuàng)建內(nèi)嵌視圖
4. 自定義屬性指令
- 創(chuàng)建指令
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
中導(dǎo)入
declarations: [
AppComponent,
HeightLightDirective
],
- 模板中使用
<p [appHeightLight]="'blue'">Highlighted in blue</p>
or
<p appHeightLight="orange">Highlighted in orange</p>
-
注意:
a.HostListener
是屬性裝飾器吹泡,用來為宿主元素添加事件監(jiān)聽骤星。
b.HostBinding
是屬性裝飾器,用來動(dòng)態(tài)設(shè)置宿主元素的屬性值爆哑。
c. Angular 會(huì)為每個(gè)匹配的元素創(chuàng)建一個(gè)指令控制器類的實(shí)例洞难,并把 Angular 的ElementRef
和Renderer
注入進(jìn)構(gòu)造函數(shù)。ElementRef
是一個(gè)服務(wù)揭朝,它賦予我們通過它的nativeElement
屬性直接訪問 DOM 元素的能力队贱。Renderer
服務(wù)允許通過代碼設(shè)置元素的樣式。