問題描述
我正在嘗試編寫一個(gè) Angular2 屬性指令來修改某些元素的行為.更具體地說,我想將屬性應(yīng)用于具有點(diǎn)擊處理程序的某些元素,并防止綁定函數(shù)在某些條件下執(zhí)行.
I am trying to write a Angular2 attribute directive to modify the behaviour of certain elements. More specifically I want to apply an attribute to certain elements that have click handlers and prevent the bound function to be executed under certain conditions.
所以現(xiàn)在我有一個(gè)元素,例如:
So now I have an element e.g.:
<button (click)="onClick(param1, param2)"></button>
onClick 是在承載按鈕元素的組件上聲明的函數(shù).
onClick is a function declared on the component that hosts the button element doing some work.
我想做的是這樣寫:
<button (click)="onClick(param1, param2)" online-only></button>
并有一個(gè)類似的指令:
@Directive({
selector: '[online-only]',
})
export class OnlineOnlyDirective {
@HostListener('click', ['$event'])
onClick(e) {
if(someCondition){
e.preventDefault();
e.stopPropagation();
}
}
}
但是單擊處理程序首先執(zhí)行,因此我的指令沒有機(jī)會停止執(zhí)行.
But click handler is executed first, thus not giving my directive the opportunity to stop its execution.
我想到的第二種方法是用我自己的處理程序替換(單擊),例如([onlineClick]="onClick")并在指令認(rèn)為合適時(shí)執(zhí)行傳遞的函數(shù),但是這樣我不能將參數(shù)傳遞給 onClick 函數(shù)和看起來有點(diǎn)奇怪.
A second approach I thought about was replacing (click) with my own handler e.g.( [onlineClick]="onClick" ) and execute the passed function when the directive thinks fit, but this way I cannot pass params to onClick function and is a bit weirder to look at.
你對做這樣的事情有什么想法嗎?
Do you have any thoughts on doing something like that?
推薦答案
我不知道有什么方法可以強(qiáng)制 Angular 先執(zhí)行某個(gè)事件處理程序.一種解決方法可能是使用自定義事件,例如:
I don't know of a way to force Angular to execute a certain event handler first. A workaround might be to use a custom event like:
<button (myClick)="onClick(param1, param2)" online-only></button>
@Directive({
selector: '[myClick]',
})
export class OnlineOnlyDirective {
@Output() myClick: EventEmitter = new EventEmitter();
@HostListener('click', ['$event'])
onClick(e) {
if(someCondition){
e.preventDefault();
e.stopPropagation();
} else {
this.myClick.next(e);
}
}
}
這篇關(guān)于Angular2指令修改點(diǎn)擊處理的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!