KilleR
KilleR

Reputation: 71

Creating new objects for select dropdowns in Angular

This is a simplified version of my problem, as my model is much bigger.

I'm generating a drop-down from a set of objects, and using the object.Name property of each to fill the select.

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

the detachmentOptions object is a generated set of 3 objects, all of which extend Detachment,

private detachmentOptions: Detachment[];

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

I want to add a detachment to my main army, based on the select, which uses the following function

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

My problem is that this uses the orignal, as JS inherantly passes by reference. No matter how many copies of DetachmentBattaliion I add, they all contain the same contents, as they are each references to the original created in the constructor.

I need to be able to create a brand-new blank object of the type selected, and I'm completely blanking on how to do this.

Object.prototype() gets the prototype, so I can't get the type, and I can't find a way to use typeof to genearate a new copy of the object.

It does not need to copy the object wholesale, I just need a method of creating the original type, without tying them together by reference.

Upvotes: 2

Views: 44

Answers (2)

Madhu Ranjan
Madhu Ranjan

Reputation: 17894

you may try below,

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

Check this Plunker!!

Upvotes: 0

shevaroller
shevaroller

Reputation: 103

You can use lodash's cloneDeep. It creates a new object instance instead of referencing the same object.

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

Upvotes: 1

Related Questions