Search code examples
angularprimeng

How to bind the value in p-autoComplete in angular


I have a search box with p-autocomplete. When I search for the value, the value is getting displayed in the suggestion.

enter image description here

I am trying to display the selected value from the suggestion in the p-autocomplete box. But when I select I am getting [Object Object]. I am new to angular. Any suggestion will be helpful. Thanks in advance!

HTML CODE

  <p-autoComplete id="dataCmpnyAuto" 
      name="dataCmpnyAuto" 
      [suggestions]="dataCmpnyAutoList" 
      (onKeyUp)="startSearch($event.target.value)"
       dropdownIcon="pi pi-angle-down" 
       (onSelect)="getCompanyList($event)"
       formControlName="dataCmpnyAuto">

       <ng-template let-i pTemplate="item">
          <div class="country-item">
            <h6>{{ i.name}}</h6>
            <div>{{ i.id}}</div>
          </div>
       </ng-template>  </p-autoComplete>                                                  

testComponent.ts

startSearch(name:any){
let Type = 0
this.pagesService.getCompanyAutoCmpList(Type, name).subscribe((results) =>{
  const responseData = results.success
  if(responseData && responseData.length>0){
    this.dataCmpnyAutoList = responseData
  }

})}

Solution

  • PrimeNG does not support selected item templates in the single selection mode. There's a workaround though. You can control the text of the selected item template:

    <p-autoComplete [field]="getSelectedItemName" ...></p-autoComplete>
    
    getSelectedItemName(item: { id: number; name: string }): string {
      return item.name;
    }
    

    StackBlitz