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?
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>
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; });
<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>
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With