Reputation: 617
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.
Thanks.
Upvotes: 1
Views: 4010
Reputation: 73357
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.
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()"/>
and then the corresponding method:
checkValidity() {
this.myForm.get('mobile').valid ?
this.myForm.get('otp').enable() : this.myForm.get('otp').disable();
}
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}]
});
DEMO: http://plnkr.co/edit/SbN3lJNjvXrE26UyVl6j?p=preview
Upvotes: 3
Reputation: 21688
you can just say form.invalid like below
<button type="submit" [disabled]="!contactForm.valid" class="btn btn-success">Verify</button>
<button type="submit" [disabled]="!contactForm.valid" class="btn btn-success">Resend</button>
which will validate entire form to be valid.
for individual form field, they have also valid and invalid field
<button type="submit" [disabled]="!opt.valid" class="btn btn-success">Verify</button>
<button type="submit" [disabled]="!opt.valid" class="btn btn-success">Resend</button>
For the input fields if the directly not working you can put them in a div and hide them
<span *ngIf="opt.invalid && (opt.dirty || opt.touched)" class="text-danger align-middle">
<input ...></input>
</span>
Upvotes: 1