Flavio Alarcon
Flavio Alarcon

Reputation: 19

Angular push and splice array elements bound to html

I have a little form like this whenever I click "add" a new row gets added.

HTML:

   <div class="tel" *ngFor="let t of tel; let i = index">
          <div class="row">
            <div class="col-md-2">
              <input type="text" class="form-control" [(ngModel)]="t.telFijo" [name]="'tfijo'+i">
            </div>
            <div class="col-md-2">
              <input type="text" class="form-control" [(ngModel)]="t.telCelular" [name]="'tcel' + i">
            </div>
            <div class="col-md-2">
              <input type="text" class="form-control" [(ngModel)]="t.anexo" [name]="'anex' + i">
            </div>
            <div class="col-md-2">
              <input type="text" class="form-control" [(ngModel)]="t.skype" [name]="'skype' + i">
            </div>
            <div id="em" class="col-md-3">
              <input type="email" class="form-control" [(ngModel)]="t.email" [name]="'email' + i">
            </div>
            <div class="col-md-1">
              <i id="trash" class="fa fa-trash" (click)="eliminar(i)"></i>
            </div>
          </div>
        </div>

Whenever I add I push an object.

  agregar() {
 const telefono = new Telefono();
this.tel.push(telefono);
}

And whenever I remove an item I splice it in the current position.

 eliminar(i) {
 this.tel.splice(i, 1);
 }

That works fine, the issue is that when I try to add a new row after I deleted one, the last two rows get deleted.

In this example I had 3 rows, deleted the middle one and then added one. Which made the previous one get deleted. I honestly have no idea why this happens. I would love to know if there is something I'm missing.

Upvotes: 1

Views: 1125

Answers (1)

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9784

In addition

agregar() {
  const telefono = new Telefono();
  this.tel.push(telefono);
}

Upvotes: 1

Related Questions