重置表单后,不会清除Angular 9表单验证器

时间:2020-05-11 20:02:07

标签: validation angular-material angular9

很抱歉,如果重复的话,但是我正在互联网上四处寻找,找不到针对我特定问题的解决方案。

问题跟随代码,这是代码:

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

export class FormComponent {
  public myForm: FormGroup;
  public myFormControl: FormControl = new FormControl('', {
    validators: [isLengthInvalid(5, 50,
      MessageConstants.MIN_VALIDATION_MSG, MessageConstants.MAX_VALIDATION_MSG)],
    updateOn: 'change'
  });

  public createAnotherChecked: boolean = false;


  constructor(private service: MyService) {
    this.myForm = new FormGroup({name: this.name});
  }

  public submitForm(): void {
    const body: NameRequest = {name: this.myName.value};
    this.service.createName(body).subscribe(response => {
      if(this.createAnotherChecked) {
          this.myFormControl.reset('');
          this.myFormControl.markAsPristine();
          this.myFormControl.markAsUntouched();
          this.myFormControl.setError(null);
      } else{
          //just do the job if checkbox is not checked and go back to main page
      }
     })
  }
....
}
export interface NameRequest {
    name: string;
}

所以这里的问题是,当我第一次在input字段中输入名称时,直到我单击该字段之外,它都不会显示验证消息,并且也不会将输入字段标记为红色,如果它少于5个字符,将方框标记为红色,并显示错误消息。当我键入内容并选中复选框时,它会保存第一个表单并打开具有相同表单的新页面,但它会显示验证消息,并在我写第一个字符时立即将输入字段标记为红色。如何以首次使用验证器的方式重置验证器。 注意:我不使用异步表单验证

我第一次赋予良好的价值:

enter image description here

我第一次输入错误的值,然后在输入字段之外单击:

enter image description here

当我选中复选框并单击“创建”按钮时,表单将返回,如图所示:

enter image description here

谢谢!

0 个答案:

没有答案