From the way you've defined the property bindings to the [(ngModel)]
directives, the differentArray
should be of the form
differentArray = [
{ first: 0, second: 0, third: 0 },
{ first: 0, second: 0, third: 0 },
{ first: 0, second: 0, third: 0 }
]
Working example: Stackblitz
Update
Instead of pushing it in the parent, you could bind the @Input()
decorator to a setter and initialize the differentArray
directly in the child. But regardless of whether you're doing in the parent or child, the most important thing to remember is the object will be pushed by reference. So any changes to one of the object will also affect other objects. So you need to use JSON.parse(JSON.stringify(obj))
to create deep clones of the obj. Try the following
parent.component.ts
export class ParentComponent {
items = ['item1', 'item2', 'item3'];
arrayOfNumbers = [1, 2, 3, 4, 5];
differentArray = { first: 0, second: 0, third: 0 };
constructor() {}
}
parent.component.html
<app-child [items]="items" [arrayOfNumbers]="arrayOfNumbers" [differentArray]="differentArray"></app-child>
child.component.ts
export class ChildComponent {
_differentArray: Array<any> = [];
@Input() items: Array<any> = [];
@Input() arrayOfNumbers: Array<any> = [];
@Input() set differentArray(obj: any) {
this.items.forEach(item =>
// notice the deep clone using `JSON.parse(JSON.stringify(obj)` here
this._differentArray.push(JSON.parse(JSON.stringify(obj)))
);
}
constructor() {}
onSelection() {
console.log('selected: ', this._differentArray);
}
}
child.component.html
<div *ngFor="let item of items; let id=index;">
<mat-form-field >
<mat-select [(ngModel)]="_differentArray[id].first" (ngModelChange)="onSelection(id)">
<mat-option *ngFor="let number of arrayOfNumbers" [value]="number">{{number}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select [(ngModel)]="_differentArray[id].second" (ngModelChange)="onSelection(id)">
<mat-option *ngFor="let number of arrayOfNumbers" [value]="number" >{{number}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field >
<mat-select [(ngModel)]="_differentArray[id].third" (ngModelChange)="onSelection(id)">
<mat-option *ngFor="let number of arrayOfNumbers" [value]="number">{{number}}</mat-option>
</mat-select>
</mat-form-field>
</div>
Working example: Stackblitz