Angular PrimeNG Autocomplete: Displaying multiple fields?

2.5k Views Asked by At

Suppose we have this scenario:

<p-autoComplete dataKey="id" field="make" emptyMessage="{{'NoDataFound' | translate}}"
    [delay]="0" [suggestions]="vehicles" [minLength]="0" appendTo="body"
    (completeMethod)="searchVehicles($event)" (onSelect)="on($event)">
    <ng-template let-vehicle pTemplate="item">
      {{vehicle.make}} {{vehicle.model}}
    </ng-template>
</p-autoComplete>

with the controller:

export class AutoCompleteDemo {

    selectedVehicle: Vehicle;

    vehicles: Vehicle[];

    searchVehicles(event) {
        this.vehiclelookupservice.getResults(event.query).then(data => {
            this.vehicles= data;
        });
    }
}

and the Vehicle object is of structure:

{
    id: int,
    make: string,
    model: string
}

The field attribute is used to display the selected object attribute (in this case make). How do I display the selected object to display make + " " + vehicle?

1

There are 1 best solutions below

2
On BEST ANSWER

You can add a label property to your Vehicle object and then, fill it with the concatenation of other fields from this object.

Something like:

this.vehiclelookupservice.getResults(event.query).then(data => {
    this.vehicles = data;
    this.vehicles.foreach(item => item.label = item.make + " " + item.vehicle);
});

Then, replace field="make" with field="label" should do the trick.