angular学习4-创建属性型指令

import {ElementRef,Input,Directive,@HostListener}
@Directive({
	selector:'[appHighlight]'
})
export class HighlightDirective{
	@Input() enterColor:string
	@Input() leaveColor:string
	@HostListener('mouseenter') onMouseenter(){
		this.highlightColor(this.enterColor)
	}
	@HoseListener('mouseleave') onMuoseleava(){
		this.highlightColor(this.leaveColor)
	}
	constructor(private el:ElementRef){
	}
	highlightColor(color:string){
	this.el.nativeElement.style.backgroundColor = color
	}
}

ElementRef 指令引用当前DOM实例对象
Directive 该装饰器用来创建指令,selector是css属性选择器
HostListener 监听事件
Input 接收外部输入
private,protect,public的其中一个作用就是创建一个与变量同名的属性并且赋值,所以才有this.el
this.el可以通过nativeElement操作原生DOM

猜你喜欢

转载自blog.csdn.net/gexiaopipi/article/details/89130257