指令写法,angular5官网文档给的很详细。
首先要创建一个文件,需注意命名规范(后缀名为xxx.directive.ts);
今天要记录的是在多个li中,右键点击之后显示出对应的菜单,直接上图吧!
右键点击在js中只需要这样写就行:
document.oncontextmenu = function(e){
e.preventDefault();
};
但是在angular中,需要单独定义指令,用@Input进行数据绑定,传递给父元素值,再用@Output将此事件发射出去,让父元素能够接收到;
指令文件:
import {Directive, ElementRef, EventEmitter, Input, OnInit, Output} from "@angular/core";
@Directive({
selector: '[cp-right-click]', //选择你
})
export class CPRightClickDirective implements OnInit{
@Input('cp-right-click') rightClick: number;//Input
将数据从绑定表达式传达到指令中。
@Output() rightClickEvent: EventEmitter<any> = new EventEmitter();
constructor(public el: ElementRef){} //ElementRef
注入到指令构造函数中。这样代码就可以访问 DOM 元素了。
ngOnInit(){
let self = this;
this.el.nativeElement.addEventListener('contextmenu', function (event) {
event.preventDefault();//阻止默认行为
self.rightClickEvent.emit(self.rightClick);//发射事件
})
}
} 父元素html文件:
<div nz-col [nzSpan]="3" *ngFor="let list of healList; let i = index" style="position: relative;">
<dl class="add-project-dl" >
<dt [cp-right-click]="i" (rightClickEvent)='rightClickHandler($event)' (mouseout)="hideCon(i)">
<img src="{{list.logopath}}"/>
<div class="play-group"
[style.display]="list.visible ? 'block' : 'none'"
(mousemove)="groupShow(i)"
(mouseout)="groupHide(i)">
<p (click)="editPlaFrom(list)">编辑</p>
<p (click)="delPlaFrom(list)">删除</p>
</div>
</dt>
<dd>{{list.name}}</dd>
</dl>
</div>
现在父元素接收到了子元素指令发射的事件,并绑定了rightClickHandler($event)事件,这时可以在父元素中定义事件,控制右键菜单的显示与隐藏;
注:定时器是为了控制鼠标划入划出时,菜单是否显示隐藏,相当于加了一层锁,滑到别处时,那么菜单操作就会被隐藏,同时又保证了流畅性;
this.healList = [];//循环肯定要有数组 此数组是动态渲染的 html中的 ‘let i = index’ 是为了获取点击元素的index
for(let i in data){
this.healList.push({
name: data[i].name,
linkpath: data[i].linkpath,
logopath: data[i].logopath,
id: data[i].id,
isdeleted: data[i].isdeleted,
visible: false
})
}
父文件中的事件:
rightClickHandler(clickIndex){
let self = this;
this.clearLockedTimeOut();
this. detailShowLock = setTimeout(function () {
self.healList.forEach(list => {
list.visible = false;
});
self.healList[clickIndex].visible = true;
}, 250);
}
//以下是划入划出控制事件
clearLockedTimeOut() {
let self = this;
if (this.detailShowLock) {
clearTimeout(self.detailShowLock);
}
if (this.detailCloseLock) {
clearTimeout(self.detailCloseLock);
}
}
hideCon(clickIndex){
let self = this;
this.clearLockedTimeOut();
this.detailCloseLock = setTimeout(function () {
self.healList[clickIndex].visible = false;
}, 250);
}
groupShow(clickIndex){
this.clearLockedTimeOut();
this.healList[clickIndex].visible = true;
}
groupHide(clickIndex){
let self = this;
this.clearLockedTimeOut();
this.detailCloseLock = setTimeout(function () {
self.healList[clickIndex].visible = false;
}, 250);
} 每天记录一点点 开心