I have a component that is subscribed to some data used to populate a table. This table uses *ngFor to loop over the array of data and output it to the page, typical stuff.
When I define my array like so importResults: ImportResults[];, my data appears to get stored as intended and I am left with an array of objects.
ngOnInit() {
// Subscribe to our subject that lets us know about the added employees
this._massEmpService.importedData.subscribe(obj => {
if (obj) {
obj.checked = false;
this.importResults = obj;
}
});
}
With this setup, I can use *ngFor without issues by simply doing:
<tbody>
<tr *ngFor="let i of importResults" >
<td>
<input type="checkbox"
id="checkbox_{{ i.QID }}"
[checked]="i.checked"
(click)="toggleSelectedEmployee(i)"
[(ngModel)]="i.checked" />
</td>
...
</tr>
</tbody>
However... when I initialize my array like so importResults: ImportResults[] = []; it alters my data structure.
This leaves me with an array of arrays of objects?
This causes me to have to do some weird nested looping on my table which doesn't seem right.
<tbody *ngFor="let res of importResults">
<tr *ngFor="let i of res" >
<td>
<input type="checkbox"
id="checkbox_{{ i.QID }}"
[checked]="i.checked"
(click)="toggleSelectedEmployee(i)"
[(ngModel)]="i.checked" />
</td>
...
</tr>
</tbody>
Is this expected behavior to need to nest stuff like this? The first way works fine for how I would expect to be able to loop but because its not initialized, I can't push new data to it which is why I had to go with the expected way of defining it Array[] = [];
Am I doing something wrong here?


pushis wrong. Use=instead. Usingpushresults in a nested array.objis an array, so when you are initializingimportResults: ImportResults[] = [];and doingthis.importResults.push(obj);, you are pushing the arrayobjinside an emptyarrayof[]. That's why it gets messed up. Instead if you dothis.importResults = obj, you won't have the problem. The other way would be to take each object fromobjandpushthem inimportResultsinstead of pushing the wholeobjarray..nextcalled on it and sent through the behavior subject which this current component is subscribed to. Data is then rendered to the page viangForand each item in the cart has a checkbox. I can check all three items in the cart. Now, if I add another item and click the button, this process repeats. By usingimportResults = objI am replacing the whole shopping cart array so now all those checked boxes are lost. If ipushit, the items already in the cart remain untouched.