基于另一个文本字段的有效性,角反应形式[disabled]属性不适用于该文本字段 [英] Angular reactive form [disabled] attribute doesn't work for text field based on validity of another text field

查看:80
本文介绍了基于另一个文本字段的有效性,角反应形式[disabled]属性不适用于该文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是角度反应形式字段的代码段.该按钮将保持禁用状态,直到我在移动字段中输入有效,但对于文本字段则无效.我希望禁用第二个输入文本字段,直到我向移动字段输入有效输入.

below is the code snippet for angular reactive form field. The button stays disable until I valid input in mobile field but the same doesn't work for text field. I want second input text field to be disabled until I enter a valid input to mobile field.

 <div id="mobile_verification">
        <input class="form-control" id="mobile" formControlName="mobile" placeholder="Mobile no." maxlength="10">
        <input class="form-control" id="otp" [disabled]= "!contactForm.controls['mobile'].valid" formControlName="otp" placeholder="OTP" maxlength="6">
        <button type="submit" [disabled]="!contactForm.controls['otp'].valid" class="btn btn-success">Verify</button>
        <button type="submit" [disabled]="!contactForm.controls['mobile'].valid" class="btn btn-success">Resend</button>
 </div>

文本字段是否还有其他方法?我是否缺少任何内容?感谢您的帮助.

Is there any another way for text field or am I missing anything? Any help is appreciated.

谢谢.

推荐答案

disabled属性不适用于反应形式的表单控件.您需要手动"启用和禁用表单字段.我可以想到几种方法.在mobile字段上使用valueChanges,然后根据mobile字段的有效性禁用/启用otp字段.

disabled attribute does not work on form controls in reactive forms. You need to "manually" enable and disable the form field. This could be done in a couple of ways that I can think of. Use valueChanges on mobile field and then disable/enable the otp field based on the validity of mobile field.

我喜欢听一些变更事件,其中(keyup)在这里可能是最合适的.您可以在模板中调用方法或使用方法的内容.我喜欢保持模板干净,并处理组件中的逻辑.因此,您可以为mobile字段设置一个事件:

I like to listen to some change event, where (keyup) would perhaps be most suitable here. You could call a method or use the content of method in template. I like to keep the template clean tho and handle logic in component. So you could set a event for the mobile field:

<input formControlName="mobile" (keyup)="checkValidity()"/>

,然后是相应的方法:

checkValidity() {
   this.myForm.get('mobile').valid ? 
   this.myForm.get('otp').enable() : this.myForm.get('otp').disable();
}

此外,如果最初这是一个空表格,则您希望将otp字段最初设置为禁用:

Also if this is an empty form initially, you would want to set the otp field as disabled initially:

this.myForm = this.fb.group({
  mobile: ['', [....]],
  otp: [{value:'' disabled:true}]
});

演示: http://plnkr.co/edit/SbN3lJNjvXrE26UyVl6j?p =预览

这篇关于基于另一个文本字段的有效性,角反应形式[disabled]属性不适用于该文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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