skip to Main Content

i am trying to make carousel dynamic by fetching the pictures of carousel from database but i am unable to set css classes correctly because of which all the pictures are being shown at once

I tried to use index of the images like if it is the 0th index which means first image then we should make it active otherwise make it just carousel-item
this is the code snippet

<div class="carousel-inner" *ngFor="let doc of   banner_arr;let i=index;">
  <h4>{{i}}</h4>
  <div class="{{i}}===0 ? 'carousel-item active' : 'carousel-item' ">
    <img src="{{doc.image_url}}"  alt="{{i}}==0?First slide:{{i}}==1?Second slide:Third slide">
  </div>
</div>

2

Answers


  1. Chosen as BEST ANSWER

    enter image description here

    just do it like this as answered by Eliseo and declare these two functions in ts file

    prevSlide() {
      this.activeIndex = (this.activeIndex === 0) ? this.banner_arr.length - 1 : this.activeIndex - 1;
    }
    
    nextSlide() {
      this.activeIndex = (this.activeIndex === this.banner_arr.length - 1) ? 0 : this.activeIndex + 1;
    }
    

  2. Sure the "*ngFor" are in the div with class carousel-item

    you can use [ngClass] or [class.active].

    Better use "binding" (the [``]) instead of interpolation

    <div class="carousel-item" [class.active]="i===0">
        <img [src]="doc.image_url" 
              [attr.alt]="i==0?First slide:i==1?'Second slide':'Third slide'">
      </div>
    </div>
    

    NOTE: I made sometime ago a bootstrap 5 carousel in Angular in this stackblitz, check the angular.json and package.json, be careful because is related to Angular 12, but should work in Angular 15 or 16.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search