角反应形式不会在Submit上重置

时间:2020-05-24 19:27:37

标签: angular typescript angular-material

**enter image description here**

无论何时我输入一些值并提交此重置表格,但都不会删除任何验证错误

我已经在StackOverflow上尝试了很多方法,但是没有解决错误的方法

我已经尝试了数小时的其他事情,但最终还是没有运气,现在我问的是问题,但是堆栈溢出说我的问题主要是代码添加了一些文本,所以我写了一些长篇幅的文章,阅读起来并不多所以请阅读代码并帮助我谢谢你

这是ts代码

read_json

这是HTML

import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {ItemCategory} from "../../models/item.model";
import {Subscription} from "rxjs";
import {AuthService} from "../../auth/auth.service";
import {mimeType} from "../validators/mime-type.validator";

@Component({
  selector: 'app-create-item',
  templateUrl: './create-item.component.html',
  styleUrls: ['./create-item.component.css']
})
export class CreateItemComponent implements OnInit {
  isLoading = false;
  form: FormGroup;
  imagePreview: string;
  categories = Object.keys(ItemCategory).map(key => ItemCategory[key])
  private authStatusSub: Subscription;


  constructor(private authService: AuthService) {

  }

  ngOnInit(): void {
    this.authStatusSub = this.authService
      .authStatusListener
      .subscribe(authStatus => {
        this.isLoading = false;
      });
    this.loadForm();
  }

  onSavePost() {
    this.form.reset()
  }

  loadForm() {
    this.form = new FormGroup({
      title: new FormControl(null, {validators: [Validators.required, Validators.minLength(3)]}),
      category: new FormControl(null, [Validators.required]),
      description: new FormControl(null, [Validators.required, Validators.minLength(10)]),
      image: new FormControl(null, [Validators.required], mimeType)
    });
  }

  onImagePicked(event: Event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({image: file});
    this.form.get('image').updateValueAndValidity();
    const reader = new FileReader();
    reader.onload = () => {
      this.imagePreview = reader.result as string;
    };
    reader.readAsDataURL(file);
  }
}

4 个答案:

答案 0 :(得分:1)

代替重置,您可以显式设置错误(为null)。

请参阅:setErrors

this.form.setErrors(null, {emitEvent: true});

或者您可以尝试:

this.form.reset({onlySelf: false, emitEvent: true});

答案 1 :(得分:1)

执行formGroup.reset()时,将为所有reset()后代调用formGroup方法。

一个FormGroup可能包含几个FormControl

这是FormControl.reset()上发生的事情:

  reset(formState: any = null, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
    this._applyFormState(formState);
    this.markAsPristine(options);
    this.markAsUntouched(options);
    this.setValue(this.value, options);
    this._pendingChange = false;
  }

Source

this.setValue(this.value, options);之后,将调用AbstractControl.updateValueAndValidity(),它会调用验证程序

(this as {errors: ValidationErrors | null}).errors = this._runValidator();

Source

因此,这就是为什么您仍然看到错误的原因。

您可以做的是添加一些条件:

<mat-error *ngIf="form.get('category').invalid && form.get('category').pristine">Please enter a valid item title</mat-error>

pristine状态表明控件没有任何更改(请注意,它与touched不同)。

答案 2 :(得分:1)

您可以将#ngForm添加到form属性中,然后在提交表单后显示错误。为form:FormGroup重置表单后,您将看不到任何错误。

这是一个简单的例子:

 <form [formGroup]="form" (submit)="onSavePost()" *ngIf="!isLoading" #_form="ngForm">

      <mat-form-field>
        <input matInput type="text" formControlName="title" placeholder="Item Title">
        <mat-error *ngIf="form.get('title').invalid && _form.submitted">Please enter a valid item title</mat-error>
      </mat-form-field>

请参见上面的代码。我添加了_form.submitted和您的title:FormControl的有效性。这只是意味着。错误文本或<mat-error>...</mat-error>仅在提交表单后可见。

答案 3 :(得分:0)

我找到了解决方法

html

<form [formGroup]="form" #formDirective="ngForm (submit)="onCreateItem(formDirective)" *ngIf="!isLoading" >

打字稿

onCreateItem(formDirective: FormGroupDirective) {

    formDirective.resetForm();
    this.form.reset();

  }