UncleFester
UncleFester

Reputation: 417

How to reset a Angular4's FormGroup to its original state?

I am learning Angular4 more specific reactive forms. I was running the Heroes demo, and I got stuck on something.

On this Plunker we have to pick a superhero, and it will show hero's addresses. I added a reset button for each address, but when I click to reset an address, it resets everything.

In the example we have:

 createForm() { //Set up form and array of addresses
    this.heroForm = this.fb.group({
      name: '',
      secretLairs: this.fb.array([]),
      power: '',
      sidekick: ''
    });
  }

  //Function to revert changes
  revert() { this.ngOnChanges(); }

  //This function will set the name from original object
  ngOnChanges() { 
    this.heroForm.reset({
      name: this.hero.name
    });

    //It will reload the form array with original values
    this.setAddresses(this.hero.addresses);
  }

  //Create new formgroups and add to formArray
  setAddresses(addresses: Address[]) {
    const addressFGs = addresses.map(address => this.fb.group(address));
    const addressFormArray = this.fb.array(addressFGs);
    this.heroForm.setControl('secretLairs', addressFormArray);
  }

This is ok, it works, but it will reset the entire form. For instance, Whirlwind has two addresses. I added a new address, and after that, I make a change to the first address. I make a mistake and want to get the original values, I click on the reset button, and it will remove my new address, and it will reset all data on the form.

How can I reset per address and not the entire form?

Thanks

Upvotes: 1

Views: 2610

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658263

You can use value or getRawValue() to read the values after initialization.

After reset() you can then set the initial values back by using setValue() with the previously read values.

See also

Upvotes: 2

Related Questions