Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 218
Ashutosh Ranjan Jha Avatar asked Sep 05 '25 04:09

Ashutosh Ranjan Jha


1 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 🚀🚀

like image 198
Muhammed Albarmavi Avatar answered Sep 07 '25 20:09

Muhammed Albarmavi