Manipulating form data
The FormGroup class contains two methods that we can use to change the values of a form programmatically:
setValue: Replaces values in all the controls of the formpatchValue: Updates values in specific controls of the form
The setValue method accepts an object as a parameter that contains key-value pairs for all the controls of the form. Let's add a button to our heroDetails form that creates a new hero in order to illustrate the usage of setValue:
- Open the
hero.component.htmlfile and add abuttonelement namedAdd herobefore the button that adds powers. - Bind the
clickevent of theAdd herobutton to a component method namedaddHero:<button (click)="addHero()">Add hero</button>
- Open the
hero.component.tsfile and add theaddHeromethod, which uses thesetValuemethod to fill in the form with details of a new hero:addHero()Â { Â Â this.heroDetails.setValue({ Â Â Â ...