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
Not sure why the other answers are trying to attach variables to the radio elements, when the radios already become part of the ngForm
therefore doing a myForm.valid
would work.
Here's mine:
<form #f="ngForm">
<input type="radio" value="male" name="gender" [(ngModel)]="gender" required> Male
<input type="radio" value="female" name="gender" [(ngModel)]="gender" required> Female
<button [disabled]="f.valid">Next</button>
</form>
Just a f.valid
should do.
Validate mat-radio-group using Angular2
<form [formGroup]="answerTypeFormGroup">
<ng-template matStepLabel>first name</ng-template>
<mat-radio-group formControlName="answerTypeCtrl" required>
<mat-radio-button value="option_1">Option 1</mat-radio-button>
<mat-radio-button value="option_2">Option 2</mat-radio-button>
<mat-radio-button value="option_3">Option 3</mat-radio-button>
</mat-radio-group>
</form>
// if answerTypeFormGroup is not valid show some error
<div *ngIf="!answerTypeFormGroup.valid" >some error</div>