This is a simplified version of my code snippet:
ngOnInit() {
//initialize form fields
this.form = this.builder.group({
name: '',
age: '',
location: '',
});
//Calling the service
this.dataService.getDetails().subscribe(
(data) => {
this.dataArray = data;
if (this.dataArray[this.count].status === 'OK') {
let docs = {};
this.someService.getDocs(this.dataArray[this.count].id).subscribe(
(data) => {
docs = data;
console.log("docs: ", docs);
this.setFormValues(docs);//setting form values
},
(err) => {
console.log(err);
console.log('An error occurred');
}
);
}
},
(err) => {
console.log(err);
console.log('Something went wrong',err);
}
);
}
After successfully printing the field values in the setFormValues()
function, I encountered an issue when I attempted to bind these values to the form
using setValue
or patchValue
. The form did not update with the fetched values from the service
.
Additional code related to this issue:
public setFormValues(doc: DocsDTO) {
if (doc!= null) {
console.log("setFormValues", doc);
this.form.patchValue({
name: doc.name == null ? '' : doc.name.text,
age: doc.age == null ? '' : doc.age.text,
location: doc.location == null ? '' : doc.location.text,
})
}
}
This is the structure of my form
:
<form [formGroup]="form">
<mat-card-content>
<input placeholder="name" [formControl]="name" id="name"
ngDefaultControl></input>
<input placeholder="age" [formControl]="age" id="age" ngDefaultControl></input>
</mat-card-content>
</mat-card>
</form>
Please note: When I do not use FormBuilder
and initialize form fields with FormControl
, and set form values with this.name.setValue()
, the process works correctly.
Being new to Angular, I am unsure of what mistake I am making in this scenario.