I am struggling with outputting data from a JSON object to a FormArray. When I try to display the data, all I get is Object object. Can anyone suggest the best way to tackle this issue and offer advice on improving my code?
Here is the StackBlitz link to my project: StackBlitz
Below is my code:
// JSON Data
[
{
"currentUser": {
"userId": 2,
"gender": "Herr",
"firstname": "Max",
"lastname": "Mustermann",
"username": "maxMustermann",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3558544d1858404641504758545b5b755258545c591b565a58">[email protected]</a>"
},
"success": true
}
]
// TypeScript Code
userForm: FormGroup;
constructor(private fb: FormBuilder, private http: HttpClient) {}
ngOnInit() {
this.http.get('/assets/data.json').subscribe((resp: any[]) => {
const data = resp;
if (data && data !== null) {
console.log('Output', data);
this.userForm = this.fb.group({
userFormArray: this.fb.array(
resp.map((param) => this.generateUserFormGroup(param))
),
});
}
});
}
private generateUserFormGroup(param) {
return this.fb.group({
gender: this.fb.control({ value: param.gender }),
firstname: this.fb.control({ value: param.firstname }),
lastname: this.fb.control({ value: param.lastname }),
username: this.fb.control({ value: param.username }),
email: this.fb.control({ value: param.email }),
});
}
// HTML Template
<form [formGroup]="userForm">
<div formArrayName="userFormArray">
<div
*ngFor="
let control of userForm.controls['userFormArray'].controls;
let i = index
"
>
<div [formGroupName]="i">
<input type="text" formControlName="gender" />
<input type="text" formControlName="firstname" />
<input type="text" formControlName="lastname" />
<input type="text" formControlName="username" />
<input type="text" formControlName="email" />
</div>
</div>
</div>
</form>