The open blogging platform. Say no to algorithms and paywalls.

6 Different Ways to Set Values for Reactive Forms

Angular basics cheatsheet: How set values to form-array?

How set values to form-array?

Photo by inlytics | LinkedIn Analytics Tool on UnsplashPhoto by inlytics | LinkedIn Analytics Tool on Unsplash

We may use reactive forms daily in our application as they support immutable nature, easy error handling, and unit test writing capabilities.

Do you know all the ways to set values in the forms?

In this article, I am covering all the methods which can be used to set values for single form control or form.

1. setValue()

this.testform.get("testcontrol").setValue(100);

We can get controls in different ways too.

this.testform.controls["testcontrol"].setValue(200);

2. patchValue()

this.testform.get('testcontrol').patchValue(testdata.id);

this.testform.controls['testcontrol'].patchValue(testdata.id);

If you want the form to figure out the patching by itself we can do something like this.

this.testform.patchValue({ testcontrol: testdata.id });

3. Patch values can work with an object, if the key matches from the response object with the form control then it will update values directly.

this.testform.patchValue({
    "testcontrol": testdata.id,
    "desc": "testdata value"
});

4. If keys from the response are different and you want to map properly before the patch then…

const { key1, key2} = response;//response from service

this.testForm.patchValue({
  key1,
  key2
});

or we can create a new object itself and pass it to form.

let obj = Object.assign({}, this.testform.getRawValue(), someClass);

this.testform.patchValue(obj);

5. Dealing with the form arrays

I have created a form array and tried to patch it this way

this.testform = this._fb.group({
    test: this._fb.array([])
});

let testformArray = this.testform.get('test') as FormArray;

for (let i of [0, 1, 2, 3]) {
    testformArray.push(new FormControl(false));
}
const data = ['atit', 'patel', 'form', 'array'];

testformArray.patchValue(data);

That's it for this topic. Thank you for reading!




Continue Learning