I have been delving into Angular4, specifically reactive forms. While experimenting with the Heroes demo, I encountered a hurdle.
On this Plunker example, we are required to select a superhero and view their corresponding addresses. I added a reset button for each address, but clicking on it resets everything instead of just that specific address.
In the provided code snippet, we see:
createForm() { //Setting up form and array of addresses
this.heroForm = this.fb.group({
name: '',
secretLairs: this.fb.array([]),
power: '',
sidekick: ''
});
}
//Function to undo changes
revert() { this.ngOnChanges(); }
//Resetting name to original value from the object
ngOnChanges() {
this.heroForm.reset({
name: this.hero.name
});
//Refreshing the form array with original values
this.setAddresses(this.hero.addresses);
}
//Creating new formgroups and adding them 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);
}
While this works fine, it ends up resetting the entire form. For instance, if Whirlwind has two addresses and I add a new one, then make a change to the first address and wish to revert back to the original values, clicking on the reset button removes the newly added address and resets all data in the form.
Is there a way to reset individual addresses without affecting the whole form?
Thank you