Я пытаюсь предотвратить событие нажатия на отключенные кнопки, другими словами, не дать пользователю, который удаляет отключенный атрибут, вызвать какое-либо действие.
На данный момент, Для этого у меня есть следующий код:
Execute action
< /code>
executeAction(): void {
if (this.someCondition) return;
// ...
}
< /code>
Works, but it isn't a good solution as I have to do it for ALL buttons in my app (and believe me, it's easy to forgot to do this and even a Linter can't help me here).
Looking for a more robust solution, I thought that directive< /code> может помочь мне: < /p>
import { Directive, HostListener, Input, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: 'button'
})
export class ButtonDirective {
@Input() set disabled(value: boolean) {
this._disabled = value != null;
this.renderer2.setAttribute(this.elementRef.nativeElement, 'disabled', `${this._disabled}`);
}
private _disabled: boolean;
constructor(
private readonly elementRef: ElementRef,
private readonly renderer2: Renderer2
) { }
@HostListener('click', ['$event'])
onClick(mouseEvent: MouseEvent) {
// nothing here does what I'm expecting
if (this._disabled) {
mouseEvent.preventDefault();
mouseEvent.stopImmediatePropagation();
mouseEvent.stopPropagation();
return false; // just for test
}
}
}
< /code>
Execute action
< /code>
executeAction(): void {
console.log('still being called');
}
< /code>
...however it does absolutely nothing. It doesn't prevent the click событие. Есть ли какое-либо решение, при котором мне не нужно контролировать само действие при его вызове?
STACKBLITZ< /п>
Подробнее здесь: https://stackoverflow.com/questions/603 ... ed-buttons