如何在 ng-template 中获取 primeng 下拉列表的索引值

How to get index value in ng-template for primeng dropdown

我试图在 ng-template 中获取 primeng 下拉列表的索引值,但它给了我空值。这是示例代码

<p-dropdown [options]="cards" [(ngModel)]="selectedCard">
 <ng-template let-card let-i="index" pTemplate="item">
  <span>{{i}}</span>
 </ng-template>
</p-dropdown>

你可以试试<span>{{cards.indexOf(card)}}</span>.

我认为 primeng 9.x 文档中没有提到 ng-template 中的 let-i="index"

如果你检查 primeng source 代码你会发现 pass 传递选项的项目所以没有关于索引的信息

 <ng-container *ngTemplateOutlet="template; context: {$implicit: option}"></ng-container>

一种方法是创建一个管道来查找传递的选项的索引基

@Pipe({
  name: 'indexOf'
})
export class IndexOfPipe implements PipeTransform {

  transform(items:any[] , item:any): any {
    return items.indexOf(item);
  }

}

例子

<p-dropdown [options]="cities" [(ngModel)]="selectedCountry" 
     optionLabel="name" [filter]="true" [showClear]="true"
    placeholder="Select a Country">

    <ng-template let-item pTemplate="item">

        <div>{{item.value.name}} {{cities | indexOf:item.value}} </div>

    </ng-template>
</p-dropdown>

demo