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);
    }
}
4
  • 2
    Can you share it in stackbiltz Commented Sep 9, 2019 at 8:26
  • Can you try to change name="colorSetQ-{{index}}" to name="colorSetQ-{{k}}" Commented Sep 9, 2019 at 8:27
  • @BunyaminCoskuner that was it! Tesekurler Commented Sep 9, 2019 at 8:32
  • @Laziale I've posted it as an answer. Can you mark it as accepted? Commented Sep 9, 2019 at 8:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

There is no need to answer typo questions - there is a specific close reason just for that category.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.