Home > Software design >  ng-select displaying [object, object]
ng-select displaying [object, object]

Time:06-17

I have an array of objects that includes an element with an object and I'm looking to display the name of the object on a selectable dropdown using ng-select. I can console log everything as expected, however when I try to display the data I am only able to show [object, object]. The correct number of objects.

HTML -

<ng-select 
  [searchable]="false"
  bindValue="id"
  bindLabel="medications.items"
  [items]="selected"
  [(ngModel)]="serviceUsersMedication">
</ng-select>

TS -

  onSelect({selected}) {
    this.selected = selected;
    const filteredMeds = this.selected.filter(item => {
    return item.medications;
  });

  this.serviceUsersMedication = filteredMeds.map(item => {
    return item.medications;
  });

  console.log('Selected:');
  console.log(this.selected);
}

looking list of medication

console log

CodePudding user response:

You're using the same variable for [items] (the collection ng-select uses to display the options) as for [(ngModel)] (used for storing/displaying the SELECTED (1) item).

You have to split this:

  • [items] should refer to the collection
  • [(ngModel]) should refer to your selected item.

Your ng-select should look like this:

<ng-select 
  [searchable]="false"
  bindValue="id"
  bindLabel="name"
  [items]="medications.items"
  [(ngModel)]="selected">
</ng-select>

Assuming you have a name attribute in the items array of medication, else change it to the attribute that makes sense to show.. selected is already containing the selected item, no need to filter for that.

Also assuming you're using ng-select from @ng-select/ng-select

  • Related