[英]Angular reactive form [disabled] attribute doesn't work for text field based on validity of another text 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>
文本字段还有其他方法吗?或者我错过了什么吗? 任何帮助表示赞赏。
谢谢。
disabled
属性不适用于反应式表单中的表单控件。 您需要“手动”启用和禁用表单字段。 我可以想到几种方法。 在mobile
字段上使用valueChanges
,然后根据mobile
字段的有效性禁用/启用otp
字段。
我喜欢听一些更改事件,其中(keyup)
可能最适合这里。 您可以在模板中调用方法或使用方法的内容。 我喜欢保持模板干净,并处理组件中的逻辑。 因此,您可以为mobile
字段设置一个事件:
<input formControlName="mobile" (keyup)="checkValidity()"/>
然后是相应的方法:
checkValidity() {
this.myForm.get('mobile').valid ?
this.myForm.get('otp').enable() : this.myForm.get('otp').disable();
}
同样,如果最初是空表单,则您希望将otp
字段最初设置为禁用:
this.myForm = this.fb.group({
mobile: ['', [....]],
otp: [{value:'' disabled:true}]
});
你可以像下面这样说form.invalid
<button type="submit" [disabled]="!contactForm.valid" class="btn btn-success">Verify</button>
<button type="submit" [disabled]="!contactForm.valid" class="btn btn-success">Resend</button>
这将验证整个表格是否有效。
对于单个表单字段,它们也具有有效和无效字段
<button type="submit" [disabled]="!opt.valid" class="btn btn-success">Verify</button>
<button type="submit" [disabled]="!opt.valid" class="btn btn-success">Resend</button>
对于输入字段,如果直接不起作用,则可以将它们放在div中并隐藏它们
<span *ngIf="opt.invalid && (opt.dirty || opt.touched)" class="text-danger align-middle">
<input ...></input>
</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.