2021-09-10

Angular 8 ng-select value object

 





Because you set the binding to ID: bindValue="ID". Remove it and it should work.

Read more about bindings here: https://ng-select.github.io/ng-select#/bindings








Source URL: https://stackblitz.com/run?file=src%2Fbindings-default-example.component.ts




html

<ng-select [items]="defaultBindingsList"
           [(ngModel)]="selectedCity">
</ng-select>



ts
import { ComponentOnInit } from '@angular/core';

@Component({
    selector: 'bindings-default-example',
    templateUrl: './bindings-default-example.component.html',
    styleUrls: ['./bindings-default-example.component.scss']
})
export class BindingsDefaultExampleComponent implements OnInit {

    defaultBindingsList = [
        { value: 1label: 'Vilnius' },
        { value: 2label: 'Kaunas' },
        { value: 3label: 'Pavilnys'disabled: true }
    ];

    selectedCity = null;

    ngOnInit() {
        this.selectedCity = this.defaultBindingsList[0];
    }
}









Angular 8 bindLabel append values


Both has no issue to show appended "full name".

Eventually go for option#2, which loop through the list to custom the display label, as the ng-select filtering in options#1 won't search through item.lastName.



Option#1
Source URL: https://stackoverflow.com/a/56531503

It is possible to display it via a custom label and item template:

<ng-select [items]="users" bindLabel="firstName"> 

  <ng-template ng-label-tmp let-item="item">
      <span >{{ item.firstName + ' ' + item.lastName }}</span>
  </ng-template>
  <ng-template ng-option-tmp let-item="item" let-search="searchTerm" let-index="index">
        <span >{{ item.firstName + ' ' + item.lastName }}</span>
  </ng-template>

</ng-select>











Displaying values with interpolation
Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters.


if using Option#1 u might need to check optional checking as below, in case u got undefined for both value to be appended.

<span >{{ item? item.firstName + ' ' + item.lastName:'' }}</span>


You can use nested ternary if

{{element.source == 1 ? 'upwork' : (element.source == 2 ? 'refer from friend' : '')}}

or probably better

export class MyComponent {
  sourceNames = {1: 'upwork', 2: 'refer from friend', 3: 'other' };
}
{{sourceNames[element.source]}}







Option#2

ng-select only accepts a string value in the attribute. I may be misunderstanding but I believe that if you say bindLabel="firstName+lastName", ng-select is attempting to reference item[firstNamelastName] which does not exist.

I think your best option is to transform the collection. You can add a .map to the end of your array declaration and use bindLabel="fullName" in your template:

[
  {firstName: "John", lastName: "Doe"},
  {firstName: "Jane", lastName: "Doe"}
].map((i) => { i.fullName = i.firstName + ' ' + i.lastName; return i; });