Angular NgForm: reset exact form filed value does not make it valid

懵懂的女人 提交于 2019-12-05 12:50:21

This seems to be a known issue. According to this the error state is calculated like:

isInvalid && (isTouched || isSubmitted)

So when you have submitted your form, the isSubmitted flag is set to true, thus the condition is fulfilled and your field is shown as red. There are some workarounds, if you were to reset the whole form, you could use resetForm instead, but here you only want to reset one field, so...

There is an suggestion to use 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);
  }
}

and declare a ErrorStateMatcher in your TS:

matcher = new MyErrorStateMatcher();

Seems to work: StackBlitz

You can make use of markAs existing functions

Something like this

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

These are actual API functions for when you want to enforce a particular state and don’t want to depend entirely on Angular decision of what should the be the state of the field

Check here how to better use the updateValueAndValidity method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!