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

标签 angular button components disabled-input

我有一个通用组件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>

最佳答案

我认为你的问题在于你 禁用您的组件,并且您在父组件中拥有click事件

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

子组件 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

关于angular - 如何防止通过 Angular 父组件点击禁用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50860288/

相关文章:

angular - 无法绑定(bind)到 'chartData',因为它不是 'div' 的已知属性,在 Angular 2 中?

java - 如何获取有关第一个 Activity 的按钮单击的信息并在第三个 Activity 中使用它? - 安卓

ios - 放大/缩小具有声音捕捉功能的UIImage Swift

javascript - ajax加载后找不到按钮

r - Speedlm更新 "need object with call component"

events - Blazor 组件 : How to communicate from grandchild to child to parent or grandchild to parent

javascript - React 同级组件之间的状态泄漏

css - 未闭合的字符串 Angular CLI 给出内容错误等

javascript - Angular 2 : why use switchMap when retrieving route params?

模板中的 Angular 6 刷新数组和 ngFor