form.resetForm不是角度函数

时间:2019-05-10 09:31:43

标签: angular

每当我在angular 7中使用form.resetForm()时,为什么会出现“ form.resetForm不是一个函数”的错误。这是我的实现方式:

.component.ts中的

form: FormGroup;

constructor(
    private userService: UserService,
    private fb: FormBuilder,
  ) { }

ngOnInit() {
    this.createForm();
  }

createForm(): void {
    this.form = this.fb.group({
      firstName:  [null, Validators.required],
      middleName: [null],
      lastName:   [null, Validators.required],
      userName:   [null, Validators.required],
      password:   [null, Validators.compose([Validators.required, Validators.minLength(4)])],
      email: [null, Validators.pattern(this.emailRegex)]
    });
  }

onSubmit(form: NgForm) {
    const obj = Object.assign({}, this.form.value);
    Object.keys(obj).forEach(key => obj[key] == undefined || obj[key] == '' ? delete obj[key] : '');
    this.submitted = true;

    if (this.form.invalid) {
      return;
    }

    this.userService.postUser(form.value).subscribe(
      res => {
        this.showSucessMessage = true;
        setTimeout(() => this.showSucessMessage = false, 4000);
        this.userService.selectedUser = {
          firstName: '',
          lastName: '',
          middleName: '',
          email: '',
          userName: '',
          password: ''
        };
        form.resetForm();
        this.serverErrorMessages = '';
      },
      err => {
        if (err.status === 422) {
          this.serverErrorMessages = err.error.join('<br/>');
        } else {
          this.serverErrorMessages = 'Something went wrong.Please contact admin.';
        }
      }
    );
  }

该文件位于.html

<form [formGroup]="form" (ngSubmit)="onSubmit(form)">
  <!-- Fist Name-->
  <input
    type="text"
    matInput
    formControlName="firstName"
    placeholder="First Name"
    required
    [ngClass]="{ 'invalid-textbox': form.submitted && !lastName.valid }"
  />
  <div *ngIf="submitted && f.firstName.errors">
    <div *ngIf="f.firstName.errors.required">
      <label class="validation-message">First Name is required</label>
    </div>
  </div>

  <!-- Middle Name-->
  <input
    type="text"
    matInput
    formControlName="middleName"
    placeholder="Middle Name"
  />

  <!-- Last Name-->
  <input
    type="text"
    matInput
    formControlName="lastName"
    placeholder="Last Name"
    required
    [ngClass]="{ 'invalid-textbox': form.submitted && !lastName.valid }"
  />
  <div *ngIf="submitted && f.lastName.errors">
    <div *ngIf="f.lastName.errors.required">
      <label class="validation-message">First Name is required</label>
    </div>
  </div>

  <!-- Fist Name-->
  <input
    type="text"
    matInput
    formControlName="userName"
    placeholder="Username"
    required
    [ngClass]="{ 'invalid-textbox': form.submitted && !lastName.valid }"
  />
  <div *ngIf="submitted && f.userName.errors">
    <div *ngIf="f.userName.errors.required">
      <label class="validation-message">Username is required</label>
    </div>
  </div>

  <!-- Email -->
  <input
    type="text"
    matInput
    formControlName="email"
    placeholder="Email"
    [pattern]="emailRegex"
    [ngClass]="{ 'invalid-textbox': form.submitted && !firstName.valid }"
  />
  <div *ngIf="submitted && f.email.errors">
    <div *ngIf="f.email.errors.pattern">
      <label class="validation-message">Invalid E-mail</label>
    </div>
  </div>

  <!-- Password -->
  <input
    type="password"
    matInput
    formControlName="password"
    placeholder="Password"
    required
    [ngClass]="{ 'invalid-textbox': form.submitted && !userName.valid }"
  />
  <div *ngIf="submitted && f.password.errors">
    <div *ngIf="f.password.errors.required">
      <label class="validation-message">Password is required</label>
    </div>
    <div *ngIf="f.password.errors.minlength">
      <label class="validation-message"
        >Password must atleast be 4 characters long.</label
      >
    </div>
  </div>

  <input type="submit" value="Sign Up" />
</form>

<!-- Success message -->
<div class="success" *ngIf="showSucessMessage">
  Saved successfully
</div>

<!-- Error message -->
<div class="alert" *ngIf="serverErrorMessages">
  {{ serverErrorMessages }}
</div>

我可以使用form.reset(),但验证不会重置。我可以在输入字段中看到验证错误。我已经将NgForm导入了我的组件和app.module.ts中。谢谢。

1 个答案:

答案 0 :(得分:1)

一种快速的解决方法是在提交时将submitted设置为false。据我所知,仅在用户单击提交按钮后才显示验证消息。

此外,为此,

if (this.form.invalid) {
  return;
}

您应该删除return语句。

我在下面做了以下更改:

if (!this.form.invalid) {

  this.userService.postUser(form.value).subscribe(
    res => {
      this.showSucessMessage = true;
      setTimeout(() => this.showSucessMessage = false, 4000);
      this.userService.selectedUser = {
        firstName: '',
        lastName: '',
        middleName: '',
        email: '',
        userName: '',
        password: ''
      };
      form.resetForm();
      this.submitted = false;
      this.serverErrorMessages = '';
    },
    err => {
      if (err.status === 422) {
        this.serverErrorMessages = err.error.join('<br/>');
      } else {
        this.serverErrorMessages = 'Something went wrong.Please contact admin.';
      }
      this.submitted = false;
    }
  );
}