[FIXED] Get index of ng-template without *ngFor

Issue

I am using primeng carousel and trying to get the index of the image that the carousel displays after an interval of 3s. I am stuck here and have tried different approaches but nothing is working for me. How can I do that?

Here’s my code:

<p-carousel
[value]="carouselImages"
[style]="{ 'margin-top': '2em' }"
[numVisible]="1"
[numScroll]="1"
[circular]="true"
[autoplayInterval]="3000"
>
<ng-template let-carouselImages let-i = "index" pTemplate="item">
  <div class="product-item">
    <div class="product-item-content">
      <div class="p-mb-3">
        <img
          [src]="carouselImages"
          alt="images to be displayed in carousel"
          class="product-image"
        />
      </div>
    </div>
    <h5>{{carouselHeadData[i]}}</h5>    //not working
    <p>{{carouselBodyData[i]}}</p>      //not working
  </div>
</ng-template>
</p-carousel>

Any help would be appreciated. Thanks!

Solution

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);
  }

}

Now you can put the pipe into carousal and you will get the index of it.

 <p-carousel
    [value]="carouselImages"
    [style]="{ 'margin-top': '2em' }"
    [numVisible]="1"
    [numScroll]="1"
    [circular]="true"
    [autoplayInterval]="3000"
    >
    <ng-template let-item pTemplate="item">
      <div class="product-item">
        <div class="product-item-content">
          <div class="p-mb-3">
            <img
              [src]="item"
              alt="images to be displayed in carousel"
              class="product-image"
            />
          </div>
        </div>
        <h5>{{carouselImages | indexOf:item}}</h5>
        <p>{{carouselImages | indexOf:item}}</p>
      </div>
    </ng-template>
    </p-carousel>

Answered By – Kaushikkumar Parmar

Answer Checked By – Mildred Charles (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published