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 form controls. If we want to fill in the details of a product in the create product component programmatically, we should use the following snippet:
this.productForm.setValue({
name: 'New product',
price: 150
});
In the preceding snippet, each key of the object passed in the setValue
method must match the name of each control in the form. If we omit one, Angular will throw an error.
If, on the contrary, we want to fill in some of the details of a product, we can use the patchValue
method:
this.productForm.patchValue({
price: 150
});
The ...