Angular ngFor with dynamic adding of objects

1k Views Asked by At

Please check the video: https://screencast-o-matic.com/watch/cqQQj2tA22

I'm adding dynamically objects to an array and would like to set the values once the objects are added. Now when I'm adding a new object to the array all the input textboxes in the loop are resetting the value shown in the textbox although the array is keeping the correct properties in the code.

This is my markup:

<div *ngFor="let colorSet of quantity.colorSets; let k=index;">
    <div>
        <label>Color Sets:</label>
        <div>
            <mat-form-field>
                <input matInput [(ngModel)]="quantity.colorSets[k].setQ" value="{{quantity.colorSets[k].setQ}}" name="colorSetQ-{{index}}" type="text">
            </mat-form-field>
        </div>
    </div>
    <div>
        <label>Price:</label>
        <div>
            <mat-form-field>
                <input matInput [(ngModel)]="quantity.colorSets[k].price" value="{{colorSet.price}}" name="colorSetPrice-{{index}}" type="text">
            </mat-form-field>
        </div>
    </div>
</div>

And then the code:

model: any = {
    TenantId: '',
    CustomFieldName: '',
    quantities: []
};

newQuantity = {
    price: '',
    rangestart: '',
    rangeend: '',
    colorSets: []
};

colorSetInfo = {
    setQ: '',
    price: ''
}

addNewPriceSet(quantitySet) {
    if (quantitySet) {
        quantitySet.colorSets.push({
            setQ: '',
            price: ''
        });
        console.log(quantitySet);
        console.log(this.model);
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

You have a typo. You don't have index in your scope (within ngFor).

Change name="colorSetQ-{{index}}" to name="colorSetQ-{{k}}"

And

name="colorSetPrice-{{index}}" to name="colorSetPrice-{{k}}"