I implemented the formgroup code in ngOnInit() and also utilized a service in ngOnInit(). However, the asynchronous nature of the form is causing issues. The full code on StackBlitz works when I use dummy JSON data within the constructor. Check out the working-form-dummyjson CODE URL here.
Although I received a response from the service by using it inside ngOnInit(), the form is not functioning properly due to the asynchronous call. You can view the code with the service implementation that is not working here.
The snippet below shows the service code where I fetch the data: this.dataService.getData().then(data => this.users=data); I attempted to include formgroup code within the service but encountered errors. Please refer to the console screenshot for the response.
https://i.sstatic.net/GK9iK.png
Here's a glimpse of my constructor code:
constructor(private dataService: DataService,private fb: FormBuilder) {
this.myForm = this.fb.group({
users: this.fb.array([])
})
this.users =[{"name":"manu","displayOrder":1,"data":[{"category":"electrical","name":"ele"}]},{"name":"divya","displayOrder":1,"data":[{"category":"tech","name":"ea_tcv"}]}];
this.test = [{"name":"manu","displayOrder":1,"data":[{"category":"electrical","name":"ele"}]},{"name":"divya","displayOrder":1,"data":[{"category":"tech","name":"ea_tcv"}]}];
}
Next, here's the ngOnInit() code which initializes the service and forms:
ngOnInit() {
console.log("ramu");
this.dataService.getData().then(data => console.log(data));
this.dataService.getData().then(data => this.users=data);
this.dataService.getData().then(data => this.test=data);
let dataArr = new FormArray([]);
dataArr.push(new FormGroup({
'name': new FormControl(this.users[0].data[0].name),
'category': new FormControl(this.users[0].data[0].category)
}));
let formArr = <FormArray>this.myForm.controls.users;
formArr.push(this.fb.group({
name: this.users[0].name,
displayOrder: this.users[0].displayOrder,
data: dataArr
}));
}