程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular 5 FormGroup重置不会重置验证器大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Angular 5 FormGroup重置不会重置验证器?

开发过程中遇到Angular 5 FormGroup重置不会重置验证器的问题如何解决?下面主要结合日常开发的经验,给出你关于Angular 5 FormGroup重置不会重置验证器的解决方法建议,希望对你解决Angular 5 FormGroup重置不会重置验证器有所启发或帮助;

它(FormGroup)行为正确。您的表单需要用户名和密码,因此,当您重置表单时,该表单应该无效(即,没有用户名/密码的表单无效)。

如果我理解正确,那么这里的问题就是为什么在您第一次加载页面(表单也是无效的)时并没有出现红色错误,而是在您单击按钮时弹出了红色错误。当您使用R_11_11845@aterial时,此问题尤其突出。

AFAIK,<mat- error>请检查的有效性FormGroupDirective,而不是FormGroup,并且重置FormGroup不会重置FormGroupDirective。这有点不方便,但要清除<mat- error>您也需要重置FormGroupDirective

为此,请在模板中定义如下变量:

<form [formGroup]="myForm" #formDirective="ngForm" 
  (ngsubmit)="submitForm(myForm, formDirectivE)">

然后在您的组件类中,调用formDirective.resetForm()

private submitForm(formData: any, formDirective: FormGroupDirectivE): voID {
    formDirective.resetForm();
    this.myForm.reset();
}

解决方法

我的页面上有一个表单,当我调用FormGroup.reset()它时,将forms类设置为,ng-prisTine ng- untouchedFormControl.hasError(...)仍然返回true。我在这里做错了什么?

模板

<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)">
  <mat-form-field>
    <input maTinput formControlName="email" />
    <mat-error *ngIf="email.hasError('required')">
      Email is a required feild
    </mat-error>
  </mat-form-field>
  <mat-form-field>
    <input maTinput type="password" formControlName="password" />
    <mat-error *ngIf="password.hasError('required')">
      password is a required feild
    </mat-error>
  </mat-form-field>
  <button type="submit">Login</button>
</form>

零件

export class MyComponent {
  private myForm: FormGroup;
  private email: FormControl = new FormContorl('',Validators.required);
  private password: FormControl = new FormControl('',Validators.required);

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.myForm = formBuilder.group({
      email: this.email,password: this.password
    });
  }

  private submitForm(formData: any): void {
    this.myForm.reset();
  }
}

大佬总结

以上是大佬教程为你收集整理的Angular 5 FormGroup重置不会重置验证器全部内容,希望文章能够帮你解决Angular 5 FormGroup重置不会重置验证器所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。