Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Radio Button Validation with ngModel

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.

like image 761
Malik Shahzad Avatar asked Dec 14 '16 13:12

Malik Shahzad


2 Answers

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; 
}
like image 151
Bazinga Avatar answered Oct 10 '22 00:10

Bazinga


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

like image 38
silentsod Avatar answered Oct 10 '22 02:10

silentsod