HJ1990
HJ1990

Reputation: 415

Angular - Reactive Form Validation for radio group

I would like to add validation on the mat-radio-group if the user has not selected any option when they submit the form. This is what I did so far but it's not working.

<mat-radio-group  formControlName="{{e.Index}}">
    <mat-label>{{ et.Title }}</mat-label>
    <mat-radio-button *ngFor="let tq of e.Items" [value]="tq" [checked]="tq.IsSelected">
      {{tq.Name}}
    </mat-radio-button>
</mat-radio-group>

TS

elements.forEach((e, i) => {
  case form.id: {
    if (e.Required) {
      a = { [name]: new FormControl('', Validators.required) };
    } else {
      a = { [name]: new FormControl('') };
    }
    
    etc ...
    break;
  }
}

Upvotes: 3

Views: 9985

Answers (1)

Eliseo
Eliseo

Reputation: 57939

If you use ReactiveForm or [(ngModel)] don't use [checked]. Angular check or not the radio button according the value of the FormControl.

It's impossible for me know what are yours "elements","a", or "e.index", but if the FormControl has Validators.required is invalid if you don't select anything. Other is that you want to show a message when submit. you can use if you has a form like

form=new FormGroup({
    control:new FormControl('',Validators.required)
  })

you can use some like

    <form [formGroup]="form">
        <mat-radio-group aria-label="Select an option" formControlName="control">
            <mat-radio-button value="1">Option 1</mat-radio-button>
            <mat-radio-button value="2">Option 2</mat-radio-button>
            <!--I used if is "touched" to don't show the error until submit-->
            <mat-error *ngIf="form.get('control').touched">Required</mat-error>
        </mat-radio-group>
        <button (click)="submit(form)">submit</button>
    </form>

And don't forget in submit mark all the controls as touched

submit(form)
{
     if (form.isValid)
     {
           ....
     }else
         form.markAllAsTouched()
      

}

Upvotes: 7

Related Questions