[英]Angular directive to stop default click event
用例是使用 Angular 創建一個指令,如果條件為真,該指令可用於停止默認(單擊)事件。 如果為 false,則允許觸發默認(單擊)事件。
下面的所有代碼都有效,除了它不會停止傳播,所以按鈕上的點擊事件處理程序仍在觸發。
HTML
<button mat-raised-button color="primary" [myDisabled]="reactiveForm.invalid" (click)="onSubmit()">A11y Disabled</button>
Typescript 指令
import { Directive, ElementRef, HostListener, Input, Renderer2, TemplateRef, ViewContainerRef } from "@angular/core";
@Directive({
selector: '[myDisabled]',
})
export class A11yDisabled {
private _isdisabled: boolean = false
constructor(
private _elementRef: ElementRef,
private _renderer: Renderer2
){}
@Input() set edjDisabled(condition: boolean) {
console.log('condition', condition);
if (condition) {
this._isdisabled = true;
this._renderer.addClass(this._elementRef.nativeElement, 'a11y-disabled');
this._renderer.setAttribute(this._elementRef.nativeElement, 'aria-disabled', 'true');
} else {
this._isdisabled = false;
this._renderer.removeClass(this._elementRef.nativeElement, 'a11y-disabled');
this._renderer.removeAttribute(this._elementRef.nativeElement, 'aria-disabled');
}
}
@HostListener('click', ['$event'])
onClick(e: any) {
console.log('mouseup', this._isdisabled);
if (this._isdisabled) {
e.stopPropagation();
e.preventDefault();
console.log('stop', this._isdisabled);
}
}
}
您可以使用 css pointer-event:none
來禁用所有點擊,而不是使用點擊事件 preventDefault
import {
Directive,
ElementRef,
Input,
Renderer2,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
@Directive({
selector: '[myDisabled]'
})
export class A11yDisabled {
private _isdisabled: boolean = false;
@Input() set edjDisabled(condition: boolean) {
console.log('condition', condition);
if (condition) {
this._isdisabled = true;
this._renderer.addClass(this._elementRef.nativeElement, 'a11y-disabled');
this._renderer.setAttribute(
this._elementRef.nativeElement,
'aria-disabled',
'true'
);
} else {
this._isdisabled = false;
this._renderer.removeClass(
this._elementRef.nativeElement,
'a11y-disabled'
);
this._renderer.removeAttribute(
this._elementRef.nativeElement,
'aria-disabled'
);
}
}
@HostBinding('style.pointerEvents') get pE() {
return this._isdisabled ? 'none' : '';
}
@HostBinding('tabindex') get tabIndex() {
return this._isdisabled ? '-1' : '';
}
constructor(private _elementRef: ElementRef, private _renderer: Renderer2) {}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.