简体   繁体   中英

ng-select displaying [object, object]

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

寻找药物清单

控制台日志

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM