1

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);
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Laziale
  • 7,965
  • 46
  • 146
  • 262

1 Answers1

1

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}}"

Bunyamin Coskuner
  • 8,719
  • 1
  • 28
  • 48
  • There is no need to answer typo questions - there is a specific close reason just for that category. – halfer Sep 19 '19 at 21:22