Angular2禁用按钮 [英] Angular2 disable button

查看:478
本文介绍了Angular2禁用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 angular2 中,我可以使用
[禁用] 属性禁用按钮,例如:

 < button [disabled] =!isValid(click)=onConfirm()>确认< /按钮> 

但我可以使用 [ngClass] [ngStyle] ?像这样:

 < button [ngStyle] ={disabled:!isValid}(click)=onConfirm() >确认< /按钮> 

谢谢。

解决方案

更新



我想知道。为什么不想使用Angular 2提供的 [禁用] 属性绑定?这是处理这种情况的正确方法。我建议你通过组件方法移动你的 isValid check。

  isValidForm ){
return this.isValid;




您试过的问题解释如下



基本上你可以在这里使用 ngClass 。但增加课程不会限制事件发生。对于有效输入引发事件,您应该将点击事件代码更改为下方。所以 onConfirm 只会在字段有效时被触发。

 < ;按钮[ngClass] ={disabled:!isValid}(click)=isValid& onConfirm()>确认< / button> b 


$ b

rel =noreferrer> 此处演示

I know that in angular2 I can disable a button with the [disable] attribute, for example:

<button [disabled]="!isValid" (click)="onConfirm()">Confirm</button>

but can I do it using [ngClass] or [ngStyle] ? Like so:

<button [ngStyle]="{disabled : !isValid}" (click)="onConfirm()">Confirm</button>

Thanks.

解决方案

Update

I'm wondering. Why don't you want to use the [disabled] attribute binding provided by Angular 2? It's the correct way to dealt with this situation. I propose you move your isValid check via component method.

isValidForm() {
    return this.isValid;
}

<button [disabled]="!isValidForm()" (click)="onConfirm()">Confirm</button>

The Problem with what you tried explained below

Basically you could use ngClass here. But adding class wouldn't restrict event from firing. For firing up event on valid input, you should change click event code to below. So that onConfirm will get fired only when field is valid.

<button [ngClass]="{disabled : !isValid}" (click)="isValid && onConfirm()">Confirm</button>

Demo Here

这篇关于Angular2禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆