网站搜索

typescript - 如何在 Angular 中重置 FormGroup?


在 Angular 中我们如何重置表单值,例如我想重置 createUserForm 的值,但它不应包含或重置我在 addControl 上添加的数据。谢谢

我尝试了 this.createUserForm.reset(); 但它会重置包括我添加的控件,而我不希望这样。只想重置 createUserForm 上的字段

#代码

  createUserForm = new FormGroup({
    emailAddress: new FormControl(),
    firstName: new FormControl(),
    lastName: new FormControl(),
    phoneNumber:  new FormControl(),
    companyName: new FormControl(),
    title: new FormControl(),
    roleId: new FormControl(),
  });

#代码 2

 getAssociatedAccount() {
    this.isInProgress = true;
    this.userService
      .getUserProfile(this.authService.authUser.nameid, this.accountId)
      .pipe(finalize(() => (this.isInProgress = false)))
      .subscribe({
        next: (res: any) => {
          if (res.isSuccess) {
            this.associatedAccount = res.data.associatedAccount;
            this.createUserForm.addControl(
              'associatedAccount',
              new FormControl(this.associatedAccount)
            );
            this.createUserForm.addControl(
              'accountId',
              new FormControl(this.accountId)
            );
          }
        },
        error: (err) => noop,
        complete: () => noop,
      });
  }

答案#1

如果你查看这里的文档,它提到你可以将值作为参数传递(https://angular.io/api/forms/FormGroup#reset)

所以在你的情况下,你可以在重置时这样做:

this.createUserForm.reset({
    emailAddress: '',
    firstName: '',
    lastName: '',
    phoneNumber:  '',
    companyName: '',
    title: '',
    roleId: '',
    associatedAccount: this.associatedAccount,
    accountId: this.accountId
});

答案#2

使用 reset() 方法来重置 Angular 响应式表单。

例子

在你的情况下,只需使用下面的方法。

this.createUserForm.reset();

更多详情...