Reputation: 21
I search the issue for several hours. but no answer.
How to disable the existing click event when a user is not logged in.
I have so many buttons to do change, so I do not want to change the old click event function.
I just want to add a appLimitedDirective for the buttons.
Any of the three positions will works.
component.html
<button
(click)="onClickEvent()"
appLimitedDirective>
Click
</button>
@Directive({
selector: '[appLimitedDirective]'
})
export class LimitedDirective implements AfterViewInit {
constructor() { }
ngAfterViewInit(): void {
// 1. if the user did not logged in, disable the click event of the button.
}
@HostListener('mousedown', ['$event']) onClick(event: MouseEvent) {
// 2. if the user did not logged in, disable the click event of the button.
}
@HostListener('click', ['$event']) onClick(event: MouseEvent) {
// 3. if the user did not logged in, disable the click event of the button.
if (!this.loggedIn) {
// all the functions do not work. the existing click function still can be executed.
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
alert('you are not logged in, please do login. then will show a popup window for login...')
return false;
}
}
}
added an example: https://stackblitz.com/edit/angular-ivy-ob2q2r
I want to just disable the existing click event. and ensure the button is clickable.
Upvotes: 0
Views: 1820
Reputation: 21
I found a method to resolve this issue.
@HostListener('mousedown', ['$event']) onClick(event: MouseEvent) {
if (!this.loggedIn) {
const currentItem = event.currentTarget as HTMLElement;
currentItem.style.pointerEvents = 'none';
alert('you are not logged in, please do login. then will show a popup window for login...');
// method 1. settimeout to reset the button.
setTimeout(() => {
currentItem.style.removeProperty('pointer-events');
}, 200);
// method 2. show a popup dialog, when user close the dialog, reset the button.
}
}
example: stackblitz
Upvotes: 1
Reputation: 1896
The best way is to disable all these buttons (better ux). You can do this by:
<button
[disabled]="userNotLoggedIn"
...
</button>
It is the same effort as setting a directive. The variable 'userNotLoggedIn' must be set in the corresponding components.
Upvotes: 0
Reputation: 71931
You can just add a disabled
host binding, pointing to the user logged in:
@Directive({
selector: 'button[appLimitedDirective]'
})
export class LimitedDirective implements AfterViewInit {
@HostBinding('disabled')
isNotLoggedIn: boolean = true;
// ...
}
It's unclear where you would get the logged in information from, but I'm sure you'll figure it out
Upvotes: 0