Search code examples
angularbootstrap-5

Why is my bootstrap carrousel not loading on Angular 17 SSR?


I'm using bootstrap, I copy the snippet from the bootstrap page, and I made a little modification to use @for because my imagen came from a service.

I leave you my code:

<div class="contenedor">
  <div class="carrusel">
    <div id="carouselExampleAutoplaying" class="carousel slide" data-bs-ride="carousel">
      <div class="carousel-inner">

        @for (slide of slides; track slide; let i = $index) {
          <div class="carousel-item active" [class.active]="i === 2">
            <img [src]="slide.file" class="d-block w-100" alt="slide {{i+1}}">
          </div>
        }

      </div>
      <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
    </div>
  </div>

My component is this:

export class HomeComponent {

  slides:Carrusel[]

  constructor(private apiService:ApiService){
    afterRender(()=>{
      this.getCarrusel()
    })
  }

  getCarrusel(){
    this.apiService.getCarrusel().subscribe((data)=>{
      this.slides = data
      console.log(this.slides)
    })
  }

}

Everything in network and application section from the browser is loading, but it doesn't show anything..!

I leave you an image to make it clear:

enter image description here

I try to load the image different ways: [src], src:"{{}}" also I try to modify the carrousel height, but this only show the buttons

I don't know what else to do. Thank you for read. Nice day


Solution

  • I don't see any reason that you should use the afterRender function.

    You can call the getCarrusel function in the ngOnInit life cycle.

    ngOnInit() {
      this.getCarrusel();
    }
    

    If you are keen on using the afterRender, you should work with changeDetectorRef.detectChanges to mutate data.

    import {
      ChangeDetectorRef
    } from '@angular/core';
    
    constructor(
      private apiService: ApiService,
      private changeDetectorRef: ChangeDetectorRef
    ) {
      afterRender(() => {
        this.getCarrusel();
      });
    }
    
    getCarrusel() {
      this.apiService.getCarrusel().subscribe((data: Carrusel[]) => {
        this.slides = data;
    
        this.changeDetectorRef.detectChanges();
      });
    }
    

    Demo @ StackBlitz