[FIXED] Assign multiple properties of an object with primeng's p-dropdown

Issue

I have an object like this assigned to the ngmodel:

export class operator {
  id: string;
  name: string;
  numUser: number;
  storeName: string;
  storeCode: number;
  activeOn: string;
}

and on my dropdown i’m assigning a list of objects like this (I’ll call it "option" for now):

[
  {
    "storeCode": 2,
    "storeName": "storeName",
    "dateOfRegistration": "12/12/12",
    "inHbltAtuCrra": "string1",
    "inNegoPmt": "string2"
  },
]

So, in my html I want to, if this ‘option’ is selected, assign storeCode and storeName to the Operator object. Is there even a way to do that? I couldn’t find anything, just one property with [(ngModel)]="operator.storeCode".

My p-dropdown:

  <p-dropdown
    [showClear]="true"
    [options]="stores"
    [(ngModel)]="operator.storeCode"
    [filter]="true"
    optionLabel="storeName"
    optionValue="storeCode"
    filterBy="storeName"
    placeholder="Choose store"
  >
  </p-dropdown>

Solution

Delete the optionValue line and the value will be the entire object by default.

  <p-dropdown
    [showClear]="true"
    [options]="stores"
    [(ngModel)]="operator"
    [filter]="true"
    optionLabel="storeName"
    filterBy="storeName"
    placeholder="Choose store"
  >
  </p-dropdown>

If you only need a few properties use the onChange event

  <p-dropdown
    [showClear]="true"
    [options]="stores"
    (onChange)="onChange($event)"
    [filter]="true"
    optionLabel="storeName"
    filterBy="storeName"
    placeholder="Choose store"
  >
  </p-dropdown>

Then in the component.ts

onChange(op: operator){
  this.operator.storeCode = op.storeCode;
  this.operator.storeName = op.storeName;
}

Answered By – Chris Hamilton

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published