Angular 组件:禁用点击事件

Gel*_*o77 6 angular-components angular

我正在创建一个像这样的可重用组件:

<my-button [isDisabled]="isDisabled" (click)="click($event)"> submit </my-button>
Run Code Online (Sandbox Code Playgroud)

当属性 isDisabled 为 true 时,我想禁用单击事件,我尝试过类似的操作,但它不起作用。

包/组件/my-button.component.html

<button  [disabled]="isDisabled" #myButton>
        <ng-content></ng-content>
</button>
Run Code Online (Sandbox Code Playgroud)

包/组件/my-button.component.ts

@ViewChild('uxButton') uxButton: ElementRef;
@Input() isDisabled: boolean = false;

this.myButton.nativeElement.parentNode.removeEventListener('click' , (e) => {
       e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)

She*_*haf 8

像这样尝试

<button  [disabled]="isDisabled" (click)="btnClick.emit($event)">
        <ng-content></ng-content>
</button>

@Input() isDisabled: boolean = false;
@Output() btnClick = new EventEmitter();
Run Code Online (Sandbox Code Playgroud)

使用Output和默认情况下,如果按钮被禁用,按钮单击事件将不起作用。利用它

<my-button [isDisabled]="isDisabled" (btnClick)="click($event)"> submit </my-button>
Run Code Online (Sandbox Code Playgroud)


Eri*_*ski 7

它也可以通过以下 CSS 解决:

# This prevents host to get a direct click
:host {
  pointer-events: none;
}

# This prevents the span inside the button to "steal" the click from the button
:host /deep/ button span {
  pointer-events: none;
}

# Now only the button can get a click 
# Button is the only smart enough to stop propagation when needed
button {
  pointer-events: auto;
}
Run Code Online (Sandbox Code Playgroud)

现在你不要像其他答案一样手动传递点击事件:你有旧的(点击)事件:D

<my-button [isDisabled]="isDisabled" (click)="click($event)"> submit </my-button>
Run Code Online (Sandbox Code Playgroud)

在您的自定义组件中,您只需要传递 disabled 属性:

<button  [disabled]="isDisabled" #myButton>
        <ng-content></ng-content>
</button>
Run Code Online (Sandbox Code Playgroud)

还要考虑从另一个 stackoverflow 答案修改的stackblitz

  • 请注意,css `pointer-events: none` 将禁用其他鼠标事件。反过来,工具提示之类的东西将不再起作用,因为没有鼠标事件被触发。 (3认同)

小智 6

如果您想保留旧版单击事件而不使用输出。有一个基于先前解决方案的组合解决方案。

我的按钮.component.html

<button [disabled]="disabled">
  <ng-content></ng-content>
</button>
Run Code Online (Sandbox Code Playgroud)

我的按钮.component.ts

export class MyButtonComponent {
  @HostBinding('style.pointer-events') get pEvents(): string {
    if (this.disabled) {
      return 'none';
    }
    return 'auto';
  }

  @Input()
  disabled: boolean = false;

 constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

您将在其中调用组件的父组件,例如app.component.html

<my-button [disabled]="isDisabled" (click)="onClickFnc()">
  <span>Save which not trigger click when button is disabled</span>
</my-button>
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以在(click)属性上检查它:

<my-button [isDisabled]="isDisabled" (click)="!isDisabled && click($event)"> submit </my-button>
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个好的答案。如果您在 100 个不同的地方使用按钮,则需要进行 100 次额外检查。 (4认同)