Angular 2's documentation tells about the form validation. But only for input fields type text. My question is for Radio Buttons.
Here is HTML:
<input type="radio" required name='gender' value='Male' [(ngModel)]='gender'>Male
<input type="radio" required name='gender' value='Female' [(ngModel)]='gender'>Female
<button type='button' [disabled]="??">Next<button>
How to set disabled property to true if user hasn't selected any value.
With template driven forms you can expose your model to a local variable and query the errors object.
<form #f="ngForm">
<input type="radio" value="male" name="gender" [(ngModel)]="gender" required #genderControl="ngModel"> Male
<input type="radio" value="female" name="gender" [(ngModel)]="gender" required> Female
<button [disabled]="genderControl.errors">Next</button>
</form>
export class App {
gender = null;
}
Since you didn't say which Forms Module (Reactive or Template driven) you were using here's a reactive forms version:
html
<form [formGroup]="radioTest">
<input type="radio" name="gender" value='Male' formControlName="gender" [(ngModel)]='gender'>Male
<input type="radio" name='gender' value='Female' formControlName="gender" [(ngModel)]='gender'>Female
<button type="button" [disabled]="radioTest.controls['gender'].invalid">Gender Button</button>
</form>
component code
radioTest: FormGroup;
gender;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.radioTest = fb.group({
gender: ['', Validators.required]
});
}
Here's a Plunker: http://plnkr.co/edit/mWhYtc2nf8hSHFbLWlEx?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With