0

I'm trying to push an object who come from template into array, but when i push the second object, the first is changed and the objects are duplicated.

I'm trying this:

<div class="modal-body">
      <select class="form-control select2-hidden-accessible" [(ngModel)]="userSelected" name="user selec" (change)="selectValorUsuario(userSelected)">
        <option *ngFor="let usuario of Usuario" [ngValue]="usuario">{{usuario.nome}}</option>
      </select>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" (click)="classicModal.hide()"
        data-dismiss="modal">Fechar</button>
      <button type="button" class="btn btn-primary" id="btnIncluirUnidadeUsuarios"
       (click)="adicionarArrUsuario()">Incluir</button>
    </div>

than in component:

selectValorUsuario(evt) {
  this.nomeUsuarioObj.id = evt.id;
  this.nomeUsuarioObj.nome = evt.nome;
  this.unidadeUsuarioArr.push(this.nomeUsuarioObj)
  console.log(this.unidadeUsuarioArr);    
}

but the result is:

enter image description here

Marco Daniel
  • 5,467
  • 5
  • 28
  • 36
  • 1
    You're pushing the same object (`this.nomeUsarioObj`) every time. – Heretic Monkey Aug 13 '19 at 13:07
  • but in each change in select, evt brings another value, how can i fix it? – Rodrigo Spinelli Aug 13 '19 at 13:10
  • Possible duplicate of [javascript .push() inserts the same object every time](https://stackoverflow.com/questions/23395602/javascript-push-inserts-the-same-object-every-time) or [Push is overwriting previous data in array](https://stackoverflow.com/q/19054997/215552), which has better answers. – Heretic Monkey Aug 13 '19 at 13:11

2 Answers2

2
/**
* you need to use code mention below
*/

selectValorUsuario(evt) {
        this.unidadeUsuarioArr.push({
            id : evt.id,
            nome: evt.nome
        })
    }
Rahul Rathore
  • 126
  • 2
  • 4
1

You are modifying the class level variable unidadeUsuarioArr.

Instead you should create a new variable inside function selectValorUsuario and then pass that variable to unidadeUsuarioArr array

selectValorUsuario(evt) {
   let obj:any = {};
   obj.id = evt.id;
   obj.nome = evt.nome;
   this.nomeUsuarioObj = obj; // In case you need the current value which is selected
   this.unidadeUsuarioArr.push(obj);
}
Chetan Khandla
  • 537
  • 5
  • 20
Alok
  • 98
  • 1
  • 6