简体   繁体   中英

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.

In addition

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM