为什么我不能像这样禁用垫击按钮?

时间:2019-05-19 20:15:35

标签: angular

我正在尝试基于“角度材质”按钮构建自定义按钮。

问题是由于某种原因,我无法再disable正确地使用按钮。样式等有效,但是由于某些原因,button中的内容似乎仍然可以在(click)事件上起作用。

请参见StackBlitz example,然后单击“ Disabled ”和“ Spinner + Disabled ”按钮。

HTML:

<button mat-stroked-button [color]="color" [disabled]="disabled || loading" [type]="type">
  <mat-icon *ngIf="icon" [class.hidden]="loading">{{icon}}</mat-icon>
  <span [class.hidden]="loading"><ng-content></ng-content></span>
  <div *ngIf="loading" class="spinner-wrapper">
    <mat-spinner [diameter]="20"></mat-spinner>
  </div>
</button>

组件:

import {Component, EventEmitter, HostListener, Input, Output} from '@angular/core';


@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.css']
})
export class ButtonComponent {

  @Input() icon: string;

  @Input() color = 'primary';

  @Input() disabled = false;

  @Input() type = 'submit';

  private _loading = false;

  @Input()
  set loading(loading: boolean) {
    this._loading = loading;
  }

  get loading(): boolean {
    return this._loading;
  }

}

样式:

:host {
  display: inline-grid;
}

.hidden {
  visibility: hidden;
}

.spinner-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

有什么办法可以防止这种情况吗?

2 个答案:

答案 0 :(得分:1)

另一个解决方案可以是CSS指针事件:无

?button.component.css

:host {
  display: inline-grid;
}

.hidden {
  visibility: hidden;
}

.spinner-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

/* ######## add this pointer-events acting classes ####### */
.disabled {
  pointer-events: all;
 }

:host{
  pointer-events: none;
 }

?button.component.html

<!-- and just add [class.disabled]="!disabled" to the button-->
<button mat-stroked-button [color]="color" [disabled]="disabled || loading" [type]="type" [class.disabled]="!disabled">
  <mat-icon *ngIf="icon" [class.hidden]="loading">{{icon}}</mat-icon>
  <span [class.hidden]="loading"><ng-content></ng-content></span>
  <div *ngIf="loading" class="spinner-wrapper">
    <mat-spinner [diameter]="20"></mat-spinner>
  </div>
</button>

https://stackblitz.com/edit/stackoverflow-56211649

答案 1 :(得分:0)

这是因为(click)事件不在按钮上,而是在app-button标签上。如果将点击处理程序传递给组件,并在button标签上设置(click)属性,则禁用该属性将不会触发。