为什么在empForm.reset()之后?必填字段标记为无效错误? [英] Why after empForm.reset(); the required fields marked as invalid error?

查看:63
本文介绍了为什么在empForm.reset()之后?必填字段标记为无效错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular Form.这是一个简单的表单,具有ename/job/sal字段,ename/job是必填项.在我提交之前,当我输入值时,验证程序可以正常工作,清除功能也可以很好地擦除填充的文本.但是,在我单击提交(调用empForm.reset())之后,必填字段标记为红色-无效字段错误,清除按钮也无法删除红色,我认为这不是合理的行为.我只想在提交后,所有字段原先都保留,而没有失败的验证红色标记.如何实现这一目标,谢谢.

i'm learning Angular Form. here is a simple form, has ename/job/sal fields, ename/job are required. BEFORE i submit, when i input values, the validators are working fine, and clear function also nicely erase the filled text. BUT, AFTER i click submit (which invokes empForm.reset()), the required fields marked as red color - invalid fields error, the clear button also cannot remove the red color, i think it's not a reasonable behavior. i only want after submit, the fields are all stay originally without failed validation red marks. how to achieve that, thanks.

感谢&问候,马丁.

Thanks & Regards, Martin.

<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
    <div class="fields-container">
        <mat-form-field>
            <input formControlName="ename" matInput placeholder=Ename>
            <mat-error *ngIf="empForm.controls['ename'].errors?.required">Ename is required.</mat-error>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="job" matInput placeholder=Job>
            <mat-error *ngIf="empForm.controls['job'].errors?.required">Job is required.</mat-error>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="sal" matInput placeholder=Salary>
        </mat-form-field>
    </div>
    <div class="buttons-container">
        <button mat-raised-button type="submit" [disabled]="empForm.invalid">Submit</button>
        <button mat-raised-button type="button" (click)="onClear()">Clear</button>
    </div>
</form>

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-emp',
  templateUrl: './emp.component.html',
  styleUrls: ['./emp.component.scss']
})
export class EmpComponent implements OnInit {
  empForm;
  constructor(private fb: FormBuilder) {
    this.empForm = this.fb.group({
      ename: ['', Validators.required],
      job: ['', Validators.required],
      sal: [1000]
    })
  }

  ngOnInit(): void {
  }

  onSubmit(){
    // save to db - TBD
    this.empForm.reset();
  }


  onClear(){
    this.empForm.reset();
  }

}

推荐答案

我认为其已知的 issue ,作为解决方法您可以尝试:

I think its known issue, as a workaround you can try:

HTML:

<form [formGroup]="empForm" #f="ngForm">
  ...
</form>

TS:

@ViewChild('f') myNgForm;

onSubmit() {
  // Service call
  this.myNgForm.resetForm();
}

工作演示

这篇关于为什么在empForm.reset()之后?必填字段标记为无效错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆