【问题标题】:Trying to push objects to array using select options and ngFor [duplicate]尝试使用选择选项和 ngFor 将对象推送到数组 [重复]
【发布时间】:2019-08-13 13:03:35
【问题描述】:

我正在尝试将来自模板的对象推送到数组中,但是当我推送第二个对象时,第一个对象被更改并且对象被复制。

我正在尝试这个:

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

但结果是:

【问题讨论】:

标签: arrays angular ngfor


【解决方案1】:
/**
* you need to use code mention below
*/

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

【讨论】:

    【解决方案2】:

    您正在修改类级别变量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);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 2020-11-18
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多