How to set the selected image as the first image to show in a bootstrap carousel in Angular?

I have created a small tuto code in which I have a list of cards. on these cards I have a click event that pass the index of this cards that I will use it later to set the first image to show in carousel. This index is past via a service shared with the created components.

for now this index is past successfully, when I receive it in carousel component put it in <ngb-carousel [activeId]="activeIndex"> , as montioned in the doc

 * The slide id that should be displayed **initially**.
 * For subsequent interactions use methods `select()`, `next()`, etc. and the `(slide)` output.
 activeId: string;

However, what I have done has no effect, because the carousel still show me the first image every time. Did I miss someting?

here you can find the source code: GitHub - agentjoseph007/modal-carousel

Any help will be much appreciated.

After looking over the carousel API a little here it appears that each individual ngbSlide can be given an id property like:
<ng-template ngbSlide id="myId"> where myId is the unique ID on the page to show. If not given it seems to generate an id by itself, but the functionality of how it goes about that isn’t clear from the documentation.

That id that is passed to each slide is what you’d pass to the ngb-carousel component at the top. Right now your using the index, of each individual slide and passing that at the ngc-carousel level, but you didn’t set the index to each individual slide like above.

I’d also recommend using an *ngFor and providing an index property. The final code should look something similar to:

<ngb-carousel (slide)="onSlide($event)" [activeId]="activeIndex">
  <ng-container *ngFor="let slide of slides; let index = index">
    <ng-template ngbSlide [id]="index">
      <div class="picsum-img-wrapper">
        <img [src]="slide.image" [alt]="side.alt">
      <div class="carousel-caption">

and your component code would look similar to:

export class MyComponent {
  activeIndex = 1; // start with the second one, rather than first, first is 0 index
  slides = [
      image: 'assets/my-slide-images/first-image.png',
      label: 'First slide label',
      content: 'Nulla vitae elit libero, a pharetra augue mollis interdum.',
      alt: 'my first slide image'

With this setup you can just update the slides array within the component with the information you want to display, and Angular will take care of the rest.

note due to how the API is described, if you have a page with multiple carousels you can’t do this, and will need to manipulate the the id with more information so its unique to each ngbcarousel. This example works for just 1 carousel on the page at a time.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.