为Angular中的选择下拉列表创建新对象



这是我问题的简化版本,因为我的模型要大得多。

我正在从一组对象中生成一个下拉订单,并使用每个对象。

<md-select [(ngModel)]="selectedDetachment" placeholder="Select a detachment">
    <md-option *ngFor="let option of detachmentOptions" [value]="option">
        {{option.Name}}
    </md-option>
</md-select>

detachmentOptions对象是3个对象的生成集,所有对象都扩展了Detachment

private detachmentOptions: Detachment[];
this.detachmentOptions = [
    new DetachmentPatrol(),
    new DetachmentBattalion(),
    new DetachmentBrigade()
];

我想根据选择以下功能

的选择,向我的主要军队添加一支支队
addDetachment() {
    if(this.selectedDetachment) {
        this.army.Detachments.push(this.selectedDetachment.constructor());
        // this.makeDetachmentOptions();
    }
}

我的问题是,这是使用Orignal,因为JS固有地通过参考通过。不管我添加了多少个DetachmentBattaliion副本,它们都包含相同的内容,因为它们每个都引用了构造函数中创建的原始内容。

我需要能够创建一个选择的类型的全新空白对象,而我对如何做到这一点。

Object.prototype()获取原型,所以我无法获得类型,我找不到使用typeof的方法来使对象的新副本恢复。

它不需要复制对象批发,我只需要一种创建原始类型的方法,而无需通过参考将它们绑在一起。

您可以使用lodash的cloneDeep。它创建一个新的对象实例,而不是引用同一对象。

import { cloneDeep } from 'lodash';
...
export class ... {
  private detachmentOptions: Detachment[];
  ...

  addDetachment() {
    if(this.selectedDetachment) {
      const selectedDetachment = cloneDeep(this.selectedDetachment);
      this.army.Detachments.push(selectedDetachment.constructor());
      // this.makeDetachmentOptions();
    }
  }
}

您可以在下面尝试,

 addDetachment() {
    if(this.selectedDetachment) {
      const prototype = Object.getPrototypeOf(this.selectedDetachment);
      const instance = Object.create(prototype);
      this.army.Detachments.push(instance);
      console.log(instance);
      console.log(this.army);
    }
  }

检查这个plunker !!

最新更新