Angularjs表单:重置反应表单字段值不会使其有效

问题描述 投票:4回答:2

我在组件的模板上有一个表单:

<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>

这是我的组件的提交处理程序:

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

它的工作原理和登录错误(传递一些随机值)我明白了

enter image description here

题。如何重置表格上的确切字段并使其真正原始且不受影响?所以它应该是有效的,而不是用UI上的红色“无效”边框标记它。

loginForm.controls.password.reset()之后,我看到loginForm.controls.password.touched是假的,loginForm.controls.password.pristine是真的,但我也看到loginForm.controls.password.status是“无效的”。如果我破解它并直接将“VALID”值分配给status属性,则红色无效边框会消失,但如果我专注于该字段然后在没有任何输入的情况下离开,它会打破丢失焦点失效。应该有合法的方式来重置表单并使其同时有效。

angular angular-material angular-forms
2个回答
3
投票

这似乎是一个已知问题。根据this,错误状态计算如下:

isInvalid && (isTouched || isSubmitted)

因此,当您提交表单时,isSubmitted标志设置为true,因此条件已满足,您的字段显示为红色。有一些解决方法,如果你要重置整个表单,你可以使用resetForm代替,但在这里你只想重置一个字段,所以......

有一个suggestion使用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);
  }
}

并在您的TS中声明一个ErrorStateMatcher:

matcher = new MyErrorStateMatcher();

似乎工作:StackBlitz


0
投票

您可以使用markAs现有功能

像这样的东西

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

这些是实际的API函数,用于强制执行特定状态并且不希望完全依赖Angular决定该字段的状态应该是什么

检查here如何更好地使用updateValueAndValidity方法

© www.soinside.com 2019 - 2024. All rights reserved.