繁体   English   中英

angular 10 表单重置触发验证错误

[英]angular 10 form reset triggers validation errors

我正在使用反应形式:

<form
  #f="ngForm"
  class="form"
  [formGroup]="registerForm"
  (ngSubmit)="onSubmit()"
  novalidate
>
  <div class="title-box-form">
    <strong>Company Information</strong>
    <div class="row">
      <div class="form-group col-12">
        <input
          type="text"
          class="form-control pink-border"
          placeholder="Company Name"
          formControlName="company_name"
        />
      </div>
      <span
        class="text-danger"
        *ngIf="
          (registerForm.get('company_name').touched || submitted) &&
          registerForm.get('company_name').errors?.required
        "
      >
        company name is required
      </span>
    </div>
  </div>
  <div class="form-group col-12">
    <input
      type="text"
      class="form-control pink-border"
      placeholder="Email Address"
      formControlName="email"
    />
  </div>
  <span
    class="text-danger"
    *ngIf="
      (registerForm.get('email').touched || submitted) &&
      registerForm.get('email').errors?.required
    "
  >
    email name is required
  </span>
  <span
    class="text-danger"
    *ngIf="
      registerForm.get('email').touched &&
      registerForm.get('email').errors?.email
    "
  >
    Enter a valid email address
  </span>
  <div class="modal-footer">
    <input type="submit" class="btn-blue" />
    <mat-spinner *ngIf="loading"></mat-spinner>
  </div>
</form>

提交后我想在我正在做的 component.ts 文件中的提交功能中重置表单

onSubmit() {
    this.submitted = true;
    if (this.registerForm.valid) {
      this.loading=true;
      
     let values = JSON.stringify(this.registerForm.value);
     //this.registerForm.reset();
     this.form.reset();
    this.form.markAsPristine();
    this.form.markAsUntouched();
    this.form.updateValueAndValidity();
}

我在用:

export class ManageCustomerComponent implements OnInit {
@ViewChild('f') form;

我尝试了reserform()markAsPristine但它们都在重置表单后触发验证错误我需要在提交后重置表单,如果在表单提交后再次显示验证,我将在我的页面顶部导入它:

import { Component, OnInit, ViewChild , ChangeDetectorRef } from '@angular/core';   
import {SidebarComponent} from '../sidebar/sidebar.component';
import {HeaderComponent} from '../header/header.component';
import { ModalDirective } from 'ngx-bootstrap/modal';

import { Validators, FormGroup, FormBuilder,FormControl,FormGroupDirective,NgForm } from     '@angular/forms';
import {ServerService} from '../server.service';
import { Router } from '@angular/router';
import { HttpClient, HttpParams } from '@angular/common/http';
import Swal from "sweetalert2"

验证

以下是完整的组件 TS 代码:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { HeaderComponent } from '../header/header.component';
import { ModalDirective } from 'ngx-bootstrap/modal';

import {
  Validators,
  FormGroup,
  FormBuilder,
  FormControl,
  FormGroupDirective,
  NgForm,
} from '@angular/forms';
import { ServerService } from '../server.service';
import { Router } from '@angular/router';
import { HttpClient, HttpParams } from '@angular/common/http';
import Swal from 'sweetalert2';

declare var $: any;

@Component({
  selector: 'app-manage-customer',
  templateUrl: './manage-customer.component.html',
  styleUrls: ['./manage-customer.component.css'],
})
export class ManageCustomerComponent implements OnInit {
  @ViewChild('f') form;
  registerForm: FormGroup;
  submitted = false;
  loading = false;
  onSubmit() {
    this.submitted = true;
    if (this.registerForm.valid) {
      this.loading = true;

      let values = JSON.stringify(this.registerForm.value);
      this.server
        .request('POST', '/company/store', {
          company_name: this.registerForm.value.company_name,
          company_email: this.registerForm.value.email,
          company_phone: this.registerForm.value.phone,
          company_phone1: this.registerForm.value.phone1,
          company_fax: this.registerForm.value.fax,
          company_parish: this.registerForm.value.parish,
          company_city: this.registerForm.value.city,
          company_person_title: this.registerForm.value.salutation,
          company_person_first_name: this.registerForm.value.first_name,
          company_person_last_name: this.registerForm.value.last_name,
          company_person_email: this.registerForm.value.email2,
          company_person_phone: this.registerForm.value.work_phone,
          company_person_mobile: this.registerForm.value.mobile_phone,
        })
        .subscribe(
          (data) => {
            this.loading = false;

            Swal.fire({
              position: 'top-end',
              icon: 'success',
              title: 'Company added succesfully',
              showConfirmButton: false,
              showCloseButton: true,
            });
            console.log(data);
            //        let elem = document.getElementById('close2');
            //
            //let evt = new MouseEvent('click', {
            //        bubbles: true,
            //        cancelable: true,
            //        view: window
            //    });
            //
            //elem.dispatchEvent(evt);
            //this.registerForm.reset();

            //this.form.form.reset();
            //this.form.form.markAsPristine();
            //this.form.form.markAsUntouched();
            //this.form.form.updateValueAndValidity();
            this.form.resetForm();
          },
          (error) => {
            this.loading = false;
          }
        );
    }
  }

  constructor(
    private fb: FormBuilder,
    private server: ServerService,
    private http: HttpClient,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    this.registerForm = this.fb.group({
      company_name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', Validators.required],
      phone1: [''],
      fax: [''],
      parish: [''],
      city: [''],
      mailing_address: [''],
      salutation: [''],
      first_name: [''],
      last_name: [''],
      email2: [''],
      work_phone: [''],
      mobile_phone: [''],
    });
  }

  ngOnInit(): void {}
  ngAfterViewInit() {
    $('.select-custom').selectpicker();
  }
}

好吧,也可能有其他方法,但正如我所见,您正在使用提交的布尔值,您可以在将表单数据提交到服务器并在 API 订阅函数中使用resetForm后将其设置为 false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM