簡體   English   中英

Angular 指令停止默認點擊事件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM