How to reset formgroup in angular?

Issue

How do we reset form values in angular , for example I wanna reset the values of createUserForm but it should not include or reset the data I have added on addControl. Thanks

I tried this.createUserForm.reset(); but it reset including the add controls I added which I dont want. Only the fields on createUserForm

#Code

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

#code 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,
      });
  }

Solution

If you see the documentation here it is mentioned that you can pass the value as an argument (https://angular.io/api/forms/FormGroup#reset)

So in your case, you can do something like this while reset :

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

Answered By – Devang Patel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published