Angular NgForm: reset the exact form of the registered value does not make it valid

I have a form on a component template:

<form (ngSubmit)="submitLogin(loginForm)" #loginForm="ngForm">
  <mat-input-container>
    <input matInput [placeholder]="'User Name'" ngModel name="username" autofocus required>
  </mat-input-container>
  <br>
  <mat-input-container>
    <input matInput [placeholder]="'Password'" ngModel type="password" name="password" required>
  </mat-input-container>
  <br>
  <button [disabled]="loginForm.invalid" mat-raised-button type="submit">
    Login
  </button>
</form>

And here is my submit handler component:

public submitLogin(loginForm: NgForm) {
  return this.authService.login(loginForm.value)
    .subscribe(
      res => this.router.navigate(['/customers']),
      error => loginForm.controls.password.reset() // this place!
    );
}

It works and with an input error (passing some random values) I see

enter image description here

Question . How can I reset exactly fileld on the Form and make it really untouched and untouched? Therefore, it must be valid without marking it with a red "invalid" border in the user interface.

loginForm.controls.password.reset() , loginForm.controls.password.touched false loginForm.controls.password.pristine true, , loginForm.controls.password.status INVALID ". VALID" status, , , , , . reset .

+3
2

, , . this, :

isInvalid && (isTouched || isSubmitted)

, , isSubmitted true, , . , reset , resetForm , reset , ...

, ErrorStateMatcher:

<input matInput 
   [placeholder]="'Password'" 
   ngModel type="password" 
   name="password" required 
   [errorStateMatcher]="matcher">

ErrorStateMatcher:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    // show errors when touched and invalid
    return (control.invalid && control.touched);
  }
}

ErrorStateMatcher TS:

matcher = new MyErrorStateMatcher();

, : StackBlitz

+2

markAs

-

this.loginForm.controls.password.reset()
this.loginForm.controls.password.markAsPristine()
this.loginForm.controls.password.markAsUntouched()
this.loginForm.controls.password.updateValueAndValidity()

API, Angular ,

, updateValueAndValidity

0

Source: https://habr.com/ru/post/1692069/


All Articles