1

I'm creating carousel with bootstrap4 and images are coming from array. My problem is that first element must have the class active.

<div id="carouselExampleFade" class="carousel slide carousel-fade" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item" *ngFor="let image of sliderImages" [ngClass]="image[0] ? 'active' : null">
      <img class="d-block w-100" [src]="image" alt="First slide">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleFade" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleFade" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
2
  • So, what's your problem actually, can you explain what is wrong? Minimal but complete example whould help to answer that. Jun 13, 2018 at 19:47
  • As I said, i need to set class .active to first element and later change this on prev next buttons, but i needed to do this with *ngFor directive, answer below is what I was looking for in 100% Jun 14, 2018 at 11:50

1 Answer 1

7

Add the following to your code to allow you to key in on the index of the ngFor objects.

<div class="carousel-item" *ngFor="let image of sliderImages let i = index" [ngClass]="{'active' : i == 0}">

  <img class="d-block w-100" [src]="image" alt="First slide">

</div>

Now you can key in on i to determine the first iteration of the loop.

3
  • pretty simple but i needed someone with fresh look on this :) Works perfect, thank you very much! Jun 13, 2018 at 17:38
  • My pleasure. I would mark it as answered so other people can find this solution more easily @JózefRzadkosz Jun 13, 2018 at 17:39
  • Yup I have ban on 3 minutes left Jun 13, 2018 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.