5

I have an array (config.lensTab) of objects which I display with an ngFor in my Html :

<tr *ngFor="let item of config.lensTab; let i = index;">
          <th scope="row">{{ i + 1}}</th>
          <th><label></label>
          <input [(ngModel)]="item.radius" class="form-control"
                             type="number" step="0.01" name="radius-{{i}}</th>
[...]

I've added a '+' button which would insert an element in my array in a given index (idx) :

  public addLens(idx: number) {
           let toAdd = new LensModel(0, 0, 0,
           new MaterialModel('Air', 0), 0, 0);
           this.config.lensTab.splice(idx + 1, 0, toAdd);
     }

When I display the content of the array with console.log, the insert operation seems to work correctly. However in my html view the line next to the new line has the same value than this new line.

I give you an easy example for understanding :

Tab : [RED, GREEN, WHITE] --> add "BLUE" at index 1 ---> [RED, BLUE, BLUE, WHITE]

What am I doing wrong ?

EDIT : this is how I initialized my config object

this.config = new ConfigModel();
this.config.lensTab = [];

this.config.lensTab.push(new LensModel(1, 2, 3, new MaterialModel('Acier', 12), 4, 5));

EDIT2 :

Before clicking the "+" button

after clicking the "+" button

plunker : https://embed.plnkr.co/DghlRr/

23
  • 1
    Have you modified the changeDetection of the component.? Commented Apr 20, 2018 at 9:51
  • 1
    I don't know what it is so probably not Commented Apr 20, 2018 at 9:53
  • can you provide some code where config is initialised.? Commented Apr 20, 2018 at 9:56
  • 1
    If you can provide a plunker, maybe i can figure it out for u Commented Apr 20, 2018 at 12:14
  • 2
    Ok i'm creating one Commented Apr 20, 2018 at 12:25

1 Answer 1

3

I have used trackBy function of the angular so that ngFor detects the change.

https://plnkr.co/edit/iyXOgVSwN2VuJT64YxrT?p=preview

<div *ngFor="let item of config.lensTab; let i = index; trackBy: trackByFn">

    trackByFn(index, item) {
return index;  }

Have updated the plunker.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.