Ashutosh Ranjan Jha
Ashutosh Ranjan Jha

Reputation: 107

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>

Upvotes: 4

Views: 13073

Answers (4)

Nevada
Nevada

Reputation: 173

let-idx="index" : Index of the current item : https://angular.io/api/common/NgForOf

Solution:

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

Other usage exemple:

<div class="container">
    <ng-template ngFor let-item [ngForOf]="items" let-idx="index">
        {{idx}}
    </ng-template>
</div>

Upvotes: 0

Denys Shevchuk
Denys Shevchuk

Reputation: 19

Initiate the index As rowIndex

let-index="rowIndex"

And then use interpolation method

{{ index + 1 }}

Upvotes: 1

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24414

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

Upvotes: 8

Omar Fendri
Omar Fendri

Reputation: 119

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.

Upvotes: 4

Related Questions