如何防止通过 angular 中的父组件点击禁用的按钮?

how to prevent clicking on a disabled button through the parent component in angular?

我有一个包含按钮元素的通用组件 app-button

按钮组件html

<button [type]="type" [disabled]="isLoading || !!disabled">
    <ng-content></ng-content>
</button>

按钮组件 ts

@Component({
  selector: 'app-button',
  templateUrl: 'views/button.component.html',
  styleUrls: ['styles/button.component.scss']
})
export class ButtonComponent implements OnInit {
  @Input() type: string;
  @Input() color: string;
  @Input() disabled: boolean;
  @Input() class: string;
  isLoading: boolean;
  constructor() {
    this.type = "submit";
  }
}

我添加(单击)到我的组件并且它工作正常。但是当我放置 disabled 属性时它会禁用按钮,但是当您单击内容时(单击)仍然有效。

<app-button (click)="signIn()" [disabled]="true">
    <span>Signin</span>
</app-button>

我认为你的问题是你是 禁用您的 child 组件并且您在父组件

中有 click 事件

一个解决方案可能是将您的 (click)="signIn()" 移动到您的子组件,它将被禁用并添加一个 @Output 装饰器以接收来自子组件的 callback

子组件html

<button [type]="type" [disabled]="isLoading || !!disabled" (click)="signIn()">
    <ng-content></ng-content>
</button>

子组件 ts

@Component({
  selector: 'app-button',
  templateUrl: 'views/button.component.html',
  styleUrls: ['styles/button.component.scss']
})
export class ButtonComponent implements OnInit {
  @Input() type: string;
  @Input() color: string;
  @Input() disabled: boolean;
  @Input() class: string;
  @Output() callback = new EventEmitter();
  isLoading: boolean;
  constructor() {
    this.type = "submit";
  }

  signIn(){
     this.callback.emit();
  }

}

父组件html

<app-button (callback)="signIn()" [disabled]="true">
    <span>Signin</span>
</app-button>

Demo StackBlitz