问题
I built my app with angular 2 and PrimeNG. I try to use directives on button click for checking user authority. Problem is; if there is no authority, do not continue button click action. But stopPropagation doesn't stop click event. How to stop process if checkAuth() returns false?
Blockquote
@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;
}
}
Directive usage on html like this;
<button type="button" pButton icon="fa fa-file-code-o" (click)="createForm()" checkAuthOnClick [allowedClaim]="systemDefinedClaims?.CreateInvoiceDesign"></button>
回答1:
Binding event by (click)
and HostBinding
just means binding two standalone events to your target elements, they will be called at the same time and won't give effects to each other which means stop any of them won't stop the other one.
You need to call click event(currently binding via (click)
) manually in your directive's click event binding via HostBinding
.
// transfer click event into directive
@Input('clickEvent') clickEvent;
@HostListener('click', ['$event, $event.target'])
onClick(event, targetElement) {
if (!this.checkAuth()) {
event.stopPropagation();
event.preventDefault();
event.cancelBuble = true;
event.stopImmediatePropagation();
this.stop.emit(event);
} else {
this.clickEvent();
}
}
See sample demo.
来源:https://stackoverflow.com/questions/50365746/stop-button-click-event-on-directive-angular-2