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.html
file and add abutton
element namedAdd hero
before the button that adds powers. - Bind the
click
event of theAdd hero
button to a component method namedaddHero
:<button (click)="addHero()">Add hero</button>
- Open the
hero.component.ts
file and add theaddHero
method, which uses thesetValue
method to fill in the form with details of a new hero:addHero()Â { Â Â this.heroDetails.setValue({ Â Â Â ...