简体   繁体   English

如何在angular中绑定p-autoComplete中的值

[英]How to bind the value in p-autoComplete in angular

I have a search box with p-autocomplete.我有一个带有 p-autocomplete 的搜索框。 When I search for the value, the value is getting displayed in the suggestion.当我搜索该值时,该值会显示在建议中。

在此处输入图像描述

I am trying to display the selected value from the suggestion in the p-autocomplete box.我试图在 p-autocomplete 框中显示从建议中选择的值。 But when I select I am getting [Object Object].但是当我 select 我得到 [Object Object]。 I am new to angular. Any suggestion will be helpful.我是 angular 的新手。任何建议都会有所帮助。 Thanks in advance!提前致谢!

HTML CODE HTML 代码

  <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测试组件.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
  }

})}

PrimeNG does not support selected item templates in the single selection mode. PrimeNG不支持单选模式下的选中项目模板。 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 StackBlitz

If you want to display name and Id to your users, then I suggest to prepare your objects array match intended output from your function that fetches data from api如果您想向您的用户显示名称和 ID,那么我建议准备您的对象数组匹配预期的 output 来自您的 function 从 api 获取数据

In your html just add field as per documentation read here在您的 html 中,只需按照此处阅读的文档添加field

<p-autoComplete  
 [suggestions]="dataCmpnyAutoList" 
(completeMethod)="....."
field="combineNameId" ...>
</p-autoComplete>

And in your Ts file, map array list to add combinedNameId key in your object在你的 Ts 文件中, map 数组列表在你的 object 中添加combinedNameId

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 .map((item:any)=>({
   ...item,
    combinedNameId: item.name + ' ' + item.id

        })
  }

})}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM