When it comes to setting values on fields, I am aware that I can choose between using
setValue
or
patchValue
However, I am currently encountering a situation where I need to avoid setting the value on each field individually.
Take a look at my form code below:
registrationForm = this._fb.group({
firstName: ['', Validators.required],
lastName: [''],
age: [''],
country: ['', Validators.required],
hobby: [''],
sport: [''],
status: [''],
country: ['', Validators.required],
...
...
});
I have an object named person containing all these properties. To set the values, I am currently doing the following (which works), but I am seeking for a BETTER approach:
registrationForm = this._fb.group({
firstName: [this.person.firstName, Validators.required],
lastName: [this.person.lastName],
age: [this.person.age],
country: [this.person.country, Validators.required],
hobby: [this.person.hobby],
sport: [this.person.sport],
status: [this.person.status],
country: [this.person.country, Validators.required],
...
...
});
Another idea I am considering is creating an object from the person object so that I can utilize either setValue or patchValue methods. Here's a rough concept:
Object
.keys(dataObject)
.map((key) => {
return { firstName: firstName, lastName: lastName, age: age ...}
});
If anyone could provide guidance in the right direction, I would greatly appreciate it! Thank you in advance!