尝试使用 select 选项和 ngFor 将对象推送到数组

Trying to push objects to array using select options and ngFor

我试图将一个来自模板的对象推入数组,但是当我推入第二个对象时,第一个被更改并且对象被复制。

我正在尝试这个:

<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>

比组件:

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

但结果是:

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

selectValorUsuario(evt) {
        this.unidadeUsuarioArr.push({
            id : evt.id,
            nome: evt.nome
        })
    }

您正在修改 class 级别变量 unidadeUsuarioArr

相反,您应该在函数 selectValorUsuario 中创建一个新变量,然后将该变量传递给 unidadeUsuarioArr 数组

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);
}