2
votes

Each formGroup using a mat-select as the only required field cannot be reset with FormGroup.reset() because validators are not reset

https://stackblitz.com/edit/material7-template-matselect-required?file=src%2Fapp%2Fapp.component.html

when submitting, the first field is empty & mark as error...

Only solution that worked for me is to use ngIf to regenerate form but its not really nice for the user that see an empty html for a sec...

Any other solution ?

Thanks !

2
That is ur problem : when submitting, the first field is empty & mark as error ? - SeleM
yes, sorry for bad english - Leix

2 Answers

0
votes

Use SetValidators to make the Validators required to nullvalidator

  this.group.controls['select'].setValidators([Validators.nullValidator])
  this.group.controls['select'].updateValueAndValidity();
2
votes

As there is already an accepted answer, I can suggest a less added lines there.

That is a bit-known bug of Material, as a workaround you can do add an ElementReference to your form tag #f="ngForm":

<form [formGroup]="quickFileForm" (ngSubmit)="saveQuickFileForm()" #f="ngForm">

Then add a @ViewChild decorator to your TS part that refer to the tag in your form:

import { Component, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  group = new FormGroup({
    select: new FormControl(null, Validators.required),
    input: new FormControl()
  });

  @ViewChild('f') myForm;

   ....
   ....
}

Do not forget to import it above from @angular/core. Then merely add:

this.myForm.resetForm();

to your method:

submit() {
    if(this.group.valid) {
      const obj = new MyObj();
      Object.assign(obj, this.group.value);

      this.survey.push(obj);
      this.myForm.resetForm(); // <-- Here you add it.
      return;
    }

    alert('not valid, try again')
  }