Búsqueda de sitios web

javascript - angular 5, formulario reactivo - reiniciar un control de formulario obligatorio no restablece el error de obligatorio debajo del campo de entrada


En la plantilla tengo un formulario que se abre al presionar un botón

     <form [formGroup]="person"
          (ngSubmit)="onSubmitNewPerson()"
          #formDirective="ngForm">

            <mat-form-field>
                <input matInput formControlName="firstName" required>
            </mat-form-field>

            <mat-form-field>
                <input matInput formControlName="lastName" #last required>
            </mat-form-field>
</form>

En el componente tengo este código-

  @ViewChild('formDirective') formDirective: FormGroupDirective;

 this.person = this.formBuilder.group({
            lastName: ['', Validators.required],
            firstName: ['', Validators.required]
        });

Después de cerrar el botón, ejecuto esta función-

   this.formDirective.resetForm();//hack that I saw in some question
    this.person.reset();

pero después de abrir nuevamente el formulario, inmediatamente veo el error rojo debajo del campo de entrada.

También probé esto

    this.person.get('firstName').markAsUntouched();
   this.person.get('lastName').markAsUntouched();
     this.person.get('firstName').markAsPristine();
    this.person.get('lastName').markAsPristine();

Pero esto tampoco funciona.

¿Alguna idea de cómo arreglarlo?

Respuesta #1

Usé lo siguiente una vez cuando quise reiniciar los validadores:

    this.person.get('firstName').clearValidators();
    this.person.get('firstName').updateValueAndValidity();

Respuesta #2

Simplemente elimina 'required' de tu plantilla HTML y si quieres mostrar un mensaje de error al salir del campo, entonces prueba esto para mostrar diferentes mensajes de error.

esta es una plantilla HTML:

<div class="form-group">
        <label for="name" class="form-control-label">
        *Amount:
        </label>
        <input type="number" name="amount" class="form-control"  [formControl]="form.controls['amount']">
        <div>
        <small *ngIf="form.controls['amount'].hasError('required') && form.controls['amount'].touched" class="text-danger">
           Please enter an amount.
        
        <small  *ngIf="form.controls['amount'].hasError('min') && form.controls['amount'].touched" class="text-danger">
             Your amount must be at least 0.01.
        
        <small  *ngIf="form.controls['amount'].hasError('max') && form.controls['amount'].touched" class="text-danger">
                Your amount cannot exceed 999999.99.
        
        </div>

Este es component.ts

 import { FormGroup, FormBuilder, Validators} from '@angular/forms';

constructor(private fb: FormBuilder) {  }

this.form = this.fb.group({
    amount: [null, Validators.compose([Validators.required, Validators.min(0.01), Validators.max(999999.99)])],
  });