我搜索了该问题几个小时。但没有答案。
当用户未登录时如何禁用现有的单击事件。
我有很多按钮需要更改,所以我不想更改旧的单击事件功能。
我只想为按钮添加一个appLimitedDirective。
三个职位中的任何一个都可以。
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;
}
}
}
添加示例:https://stackblitz.com/edit/angular-ivy-ob2q2r
我只想禁用现有的单击事件。并确保该按钮是可点击的。
您可以仅添加disabled
主机绑定,指向登录的用户:
@Directive({
selector: 'button[appLimitedDirective]'
})
export class LimitedDirective implements AfterViewInit {
@HostBinding('disabled')
isNotLoggedIn: boolean = true;
// ...
}
目前尚不清楚您将从何处获取登录信息,但我确定您会知道的
最好的方法是禁用所有这些按钮(更好的ux)。您可以通过以下方式做到这一点:
<button
[disabled]="userNotLoggedIn"
...
</button>
这与设置指令相同。必须在相应的组件中设置变量'userNotLoggedIn'。
我找到了解决此问题的方法。
@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.
}
}
示例:stackblitz