[英]Stop Button Click Event On Directive Angular 2
我用 angular 2 和 PrimeNG 構建了我的應用程序。 我嘗試使用按鈕單擊指令來檢查用戶權限。 問題是; 如果沒有權限,不要繼續按鈕點擊動作。 但是 stopPropagation 不會停止單擊事件。 如果 checkAuth() 返回 false,如何停止進程?
塊引用
@Directive({
selector: '[checkAuthOnClick]'
})
export class CheckAuthorizationOnClickDirective {
user: Observable<User>;
@Input() allowedClaim: any;
observer: MutationObserver;
constructor(private element: ElementRef, private store: Store<fromRoot.State>) {
this.element = element.nativeElement;
}
@Output()
stop: EventEmitter<Event> = new EventEmitter;
@HostListener('click', ['$event, $event.target'])
onClick(event, targetElement) {
if (!this.checkAuth()) {
event.stopPropagation();
event.preventDefault();
event.cancelBuble = true;
event.stopImmediatePropagation();
this.stop.emit(event);
}
}
private checkAuth(): boolean {
this.user = this.store.select(fromRoot.currentUser);
if (this.user != undefined && this.allowedClaim != undefined) {
var hasClaim = false;
var description;
this.user.subscribe(x => {
if (Array.isArray(this.allowedClaim)) { //Gelen/Giden Faturaları görüntüleme yetkileri tümü ve kendisine ait o.ş birden çok olduğu için app.routes'ta array olarak tanımlandı.
for (let i = 0; i < this.allowedClaim.length; i++) {
hasClaim = x.hasClaim(this.allowedClaim[i])
if (hasClaim)
break;
}
description = this.allowedClaim[0].Description;
}
else {
hasClaim = x.hasClaim(this.allowedClaim);
description = this.allowedClaim.Description;
}
});
if (hasClaim == false) {
var message = "Bu işlem için yetkiniz yoktur.";
if (description != undefined) {
message = description + ' yetkiniz yoktur.'
}
this.store.dispatch(new ui.ToastMessagePushAction({ severity: 'warning', summary: message, detail: '' }));
}
}
return hasClaim;
}
}
像這樣在 html 上使用指令;
<button type="button" pButton icon="fa fa-file-code-o" (click)="createForm()" checkAuthOnClick [allowedClaim]="systemDefinedClaims?.CreateInvoiceDesign"></button>
通過(click)
和HostBinding
綁定事件只是意味着將兩個獨立事件綁定到您的目標元素,它們將同時被調用並且不會相互影響,這意味着停止其中任何一個都不會停止另一個。
您需要通過HostBinding
在指令的點擊事件綁定中手動調用點擊事件(當前綁定通過(click)
)。
// transfer click event into directive
@Input('clickEvent') clickEvent;
@HostListener('click', ['$event, $event.target'])
onClick(event, targetElement) {
if (!this.checkAuth()) {
event.stopPropagation();
event.preventDefault();
event.cancelBubble = true;
event.stopImmediatePropagation();
this.stop.emit(event);
} else {
this.clickEvent();
}
}
請參閱示例演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.