Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 ng-select how to add two values to 'bindLabel'?

I want to have ng-select with two values in property bindLabel. I have something like this:

<ng-select placeholder="{{'TASKS.FOR_WHO' | translate }}"
                           name="users"  [items]="users" bindLabel="firstName" >

 </ng-select>

But in bind label i want to have bindLabel= firstName + lastName. Like this:

<ng-select placeholder="{{'TASKS.FOR_WHO' | translate }}"
                           name="users"  [items]="users" bindLabel="firstName+lastName">

 </ng-select>

How to achieve this?

like image 632
Kacper Kapela Avatar asked Jul 19 '18 10:07

Kacper Kapela


4 Answers

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>
like image 137
michal.jakubeczy Avatar answered Oct 31 '22 14:10

michal.jakubeczy


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; });
like image 45
Kevin Avatar answered Oct 31 '22 15:10

Kevin


<ng-select [items]="users" bindLabel="firstName"> 
    <ng-template ng-label-tmp let-item="item" let-clear="clear">
        <span class="ng-value-label">{{item.firstName + ' ' + item.lastName}}</span>
        <span class="ng-value-icon right" (click)="clear(item)">×</span>
    </ng-template>
</ng-select>
like image 7
Temo Kiknadze Avatar answered Oct 31 '22 13:10

Temo Kiknadze


If you want to return custom value , the easiest way to do is to define bindLabel="fullName" and return value from component, for example:

this.adaptedLoans = this.adaptedLoans.map(item => {
    return {
        "id": item.customer.id,
        "name": item.customer.name,
        "creditLimit": item.creditLimit,
        "creditor": item.creditor,
        "fullName": item.creditLimit + ' ' + 'CHF' + ' ' + this.translate.instant('filter_at') + ' ' + item.customer.name
    }
});
like image 2
Mile Mijatović Avatar answered Oct 31 '22 14:10

Mile Mijatović