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

Viewed 4117

I am trying to get index value in ng-template for primeng dropdown but its giving me empty value. Here is sample code

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

if you check primeng source code you will find that the pass the item of the passed options so there is no information about the index

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

one way is to create a pipe the going to find the index base of the passed option

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

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

}

example

<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

You can try <span>{{cards.indexOf(card)}}</span>.

I think that let-i="index" within ng-template is not mentionned in primeng 9.x documentation.

Initiate the index As rowIndex

let-index="rowIndex"

And then use interpolation method

{{ index + 1 }}
Related