Angular 2 Radio Button Validation with ngModel

2019-04-05 12:26发布

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.

4条回答
Viruses.
2楼-- · 2019-04-05 13:05

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; 
}
查看更多
叼着烟拽天下
3楼-- · 2019-04-05 13:26

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

查看更多
该账号已被封号
4楼-- · 2019-04-05 13:29

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>
查看更多
The star\"
5楼-- · 2019-04-05 13:30

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.

查看更多
登录 后发表回答