在第四章的时候我们学习了angular
的通用指令(通用指令地址),本章中我们自定义指令。
本人理解自定义指令是扩展传统的HTML
语法,类似传递HTML语法中的class,style,id
自定义指令分下列几种
- 1、属性指令
- 普通的属性指令
- 为指令绑定输入
- 响应用户操作
- 2、结构指令
一、新建一个工程,创建基本的结构
- ng new directivedemo 创建工程
- ng g directive mydirective/mydir1 在一个指令文件夹下创建一个mydir1指令
- ng g component dirdemo01 创建一个demo组件
使用angular-cli
创建就不需要手动去app.module.ts
模块试图类中添加自己创建的指令Mydir1Directive
二、普通的属性指令的使用
import {Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[appMydir1]' //appMydir1表示指令名称
})
export class Mydir1Directive {
//ElementRef表示真实的Dom元素
constructor(el:ElementRef) {
el.nativeElement.style.backgroundColor = "#f00";
}
}
//html代码中使用
<p appMydir1>
dirdemo01 works!
</p>
三、为指令绑定输入
这种方式相对于上面那种方式更加的灵活,外面传递参数进去(简单的是组件间的数据交互)
import {Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[appMydir1]',
//inputs:['appMydir1']
})
export class Mydir1Directive {
private _defaultColor='green';
private el:HTMLElement;
@Input("appMydir1") //这个也可以删除把inputs:['appMydir1']放出来
set appMydir1(colorName:string){
console.log(colorName);
this.setStyle(colorName);
};
constructor(el:ElementRef){
this.el=el.nativeElement;
this.setStyle(this._defaultColor);
}
private setStyle(color:string){
this.el.style.backgroundColor=color;
}
}
//html代码
<p [appMydir1]="colorName">
dirdemo01 works!
</p>
<input type="button" value="红色" (click)="colorName='red'"/>
<input type="button" value="绿色" (click)="colorName='#360'"/>
<input type="button" value="蓝色" (click)="colorName='blue'"/>
四、响应用户操作
@HostListener
装饰器指向使用属性指令的DOM
元素,使得DOM
元素的事件与指令关联起来
import {Directive, ElementRef, Input, HostListener} from '@angular/core';
@Directive({
selector: '[appMydir2]',
inputs:['appMydir2']
})
export class Mydir2Directive {
private _defaultColor = "yellow";
private el: HTMLElement;
private backgroundColor:string;
//@Input("appMydir2") backgroundColor:string;
constructor(el:ElementRef) {
this.el = el.nativeElement;
this.setStyle(this._defaultColor);
}
@HostListener("click") onClick(){
this.setStyle(this.backgroundColor || this._defaultColor);
}
setStyle(color:string){
this.el.style.backgroundColor = color;
}
}
//html代码
<p [appMydir2]="'red'">
dirdemo01 works!
</p>
五、结构指令,angular
中结构指令是指对DOM
新增与删除类似ngIf
这样的
现在模拟
ngIf
的功能
需要注入这两个服务
* TemplateRef可以用来访问组件中的模板
* ViewContainerRef可作为试图内容渲染器
//自定义指令的代码
import {Directive, TemplateRef, ViewContainerRef} from '@angular/core';
@Directive({
selector: '[appMydir3]',
inputs:["appMydir3"]
})
export class Mydir3Directive {
set condition(newCondition:boolean){
if(newCondition){
this.viewContainer.createEmbeddedView(this.templateRef);
}else {
this.viewContainer.clear();
}
}
constructor(
private templateRef:TemplateRef<any>,
private viewContainer:ViewContainerRef
){}
}
//html代码
<div class="box" *appMydir3="true"></div>
<div class="box" *appMydir3="false"></div>