Arun s
Arun s

Reputation: 945

Array object in angular always default to 0 while deleting an object from the middle and adding a new object

I am trying to perform a simple array addition and deletion operations in Angular. Value inside array default to 0 while deleting an object from the middle and adding a new object .


I have attached a plunkr url below. Please open the plunkr and perform the following steps: https://plnkr.co/edit/SU9XqcP3eDPZQD3A

1) Click on Add New button. a 3rd row will be created.
2) Type a value in the new text box other than 0.
3) Delete the 2nd row.
4) Again click on Add New button.


Expected behaviour: New row (3rd row) should be added with default value as 0 and no change to 1st and 2nd row values.

Current behaviour: 2nd and 3rd row(newly added) will default to value 0 in the text box even though there is a nonzero value in 2nd row. But the value binded to variable is proper.

 <div *ngFor="let empId of empList; let i=index" class="col-sm-12">
        <div class="form-group row">
          <input type="text" [(ngModel)]="empId.value" name="name-{{i}}" class="form-control col-sm-3" required />
          <button (click)="deleteRow(i)" class="col-sm-3">Delete</button>
          Value entered : {{empId.value}}
        </div>
        <br />
    </div>

Can anyone please suggest why this is happening.? nb: The value defaulting to 0 is happening in input text box only.

Upvotes: 2

Views: 527

Answers (1)

Radik
Radik

Reputation: 2795

for ngModel need to use trackBy function in ngFor

also you can use for input name some unique id instead of index, index based name can lead to bug when ngModel lost input after ngFor updates

@Component({
  selector: 'my-app',
  template: `
  <form>
    <div *ngFor="let empId of empList; let i=index;trackBy:trackByFn" class="col-sm-12">
        <div class="form-group row">
          <input type="text" [(ngModel)]="empId.value" name="name-{{empId.id}}" class="form-control col-sm-3" required />
          <button (click)="deleteRow(i)" class="col-sm-3">Delete</button>
        Value entered is {{empId.value}}
        </div>

        <br />
    </div>
    <div>
    <button (click)="add()">Add new</button>
    </div>
    <div>{{empList|json}}</div>
  </form>
  `,
})
export class App {
  nextid = 0;

  empList:any[] = [];
  constructor() {
    this.empList=[
      {'value':'3', id: this.getId()},
      {'value':'4', id: this.getId()}]
  }
  add() {
    this.empList.push({value: '0', id: this.getId() });
  }
  deleteRow(index){
    this.empList.splice(index,1);
  }

  trackByFn = (index, item) => item.id;

  getId() {
    this.nextid = this.nextid + 1;
    return this.nextid;
  }
}

Upvotes: 0

Related Questions