Angular指令来停止默认的点击事件



这个用例是,使用Angular创建一个指令,当某个条件为真时,该指令可以用来停止默认的(click)事件。如果为false,则允许触发默认(click)事件。

下面的所有代码都可以工作,除了它不会停止传播,所以按钮上的click事件处理程序仍在触发。

HTML

<button mat-raised-button color="primary" [myDisabled]="reactiveForm.invalid" (click)="onSubmit()">A11y Disabled</button>

打印稿指令

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);
}
}

}

你可以使用csspointer-event:none来禁用所有的点击

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) {}
}

工作示例

相关内容

  • 没有找到相关文章

最新更新