Sangram Patil
Sangram Patil

Reputation: 138

PrimeNg dropdown : how to set multiple fieids as selected text

<p-autoComplete name="student" [(ngModel)]="student" [ngModelOptions]="{standalone: true}" field="firstName" [forceSelection]="false" [suggestions]="filteredStudents"
   (completeMethod)="filterStudents($event)" [size]="30" [minLength]="1" placeholder="Hint: type 'v' or 'f'" [dropdown]="true">
   <ng-template let-student pTemplate="item">
     <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
       <div style="font-size:18px;float:none;margin:10px 10px 0 0">{{student.firstName+' '+student.lastName}}</div>
     </div>
   </ng-template>
</p-autoComplete>

This works fine, but selected item appears as the firstName only.. I need to see the selected student as firstName+' '+lastName, What changes I have to do for achieving the desired result? Thanks in advance..

Upvotes: 2

Views: 5118

Answers (2)

Kamil
Kamil

Reputation: 592

Answer for those, who come here from Google:

There is an ng-template specially for that purpose. To display custom label for expanded options list, you should use pTemplate="item"

<ng-template let-student pTemplate="item">
    <div class="flex align-items-center">
        <div>{{student.lastName}} {{student.firstName}}</div>
    </div>
</ng-template>

For already selected option, it should be pTemplate="selectedItem"

<ng-template let-student pTemplate="selectedItem">
    <div class="flex">
        <div>{{student.lastName}} {{student.firstName}}</div>
    </div>
</ng-template>

Upvotes: 0

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

As primeng doesn't provide desired feature. But you can achieve it after modifying your code as:

HTML

<p-autoComplete name="student" 
    [ngModel]="displayValue" <============= here
    [ngModelOptions]="{standalone: true}" 
    [forceSelection]="false" 
    [suggestions]="filteredStudents"
    (completeMethod)="filterStudents($event)" [size]="30" [minLength]="1" placeholder="Hint: type 'v' or 'f'" [dropdown]="true" 
    (onSelect)="onSelect($option)">
    <ng-template let-student pTemplate="item">
        <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
            <div style="font-size:18px;float:none;margin:10px 10px 0 0">{{student.firstName+' '+student.lastName}}</div>
        </div>
    </ng-template>
</p-autoComplete>

Here I used one way binding only.

component

displayValue: string; 

onSelect($value) {
    this.student = $value;
    this.displayValue = this.student.firstName + ' ' + this.student.lastName;
}

Working stackblitz: https://stackblitz.com/edit/angular-isg6ez

Upvotes: 1

Related Questions