【问题标题】:how to prevent clicking on a disabled button through the parent component in angular?如何防止通过角度的父组件单击禁用的按钮?
【发布时间】:2018-11-24 09:31:17
【问题描述】:

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

【问题讨论】:

  • 你不能禁用一个组件
  • 在您的signIn 函数中,您检查事件目标的属性是否已禁用...或者如果您知道单击事件处理程序将被禁用,则不要附加点击事件处理程序
  • 如果你想坚持这个逻辑,我想你可以绑定点击&lt;button&gt;标签本身并将函数作为组件的属性传递。
  • 但是有没有办法让它对所有按钮都通用?我已经有很多用途了:)
  • @Gbac 你的意思是像这样的[click]="func",然后在组件@Input() func: any; if(!disabled) { func(); }

标签: angular button components disabled-input


【解决方案1】:

我认为你的问题是你是 禁用您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    相关资源
    最近更新 更多