2021-09-10

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







No comments:

Google Referrals