angularswiper.jsangular17

Swiper and Material Grid List in Angular 17


I followed this approach to use swiper elements in my angular 17 ssr project. If I use swiper inside material GridList then the view is not rendered properly. Are there any rendering timing issues? StackBlitz minimal working example.

import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { MatGridListModule } from '@angular/material/grid-list';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ MatGridListModule ],
  template: `
    <p>Swipe to change slides</p>
    <mat-grid-list cols="2" rowHeight="100px">
      <mat-grid-tile [colspan]="2" [rowspan]="2">
        <swiper-container>
          <swiper-slide>Slide 1</swiper-slide>
          <swiper-slide>Slide 2</swiper-slide>
          <swiper-slide>Slide 3</swiper-slide>
          <swiper-slide>Slide 4</swiper-slide>
        </swiper-container>
      </mat-grid-tile>
    </mat-grid-list>`,
  styles: [
    `swiper-slide {
      height: 400px
    }
    swiper-slide:nth-of-type(1) {
      background-color: red;
    }
    swiper-slide:nth-of-type(2) {
      background-color: green;
    }
    swiper-slide:nth-of-type(3) {
      background-color: blue;
      color: white;
    }
    swiper-slide:nth-of-type(4) {
      background-color: yellow;
    }`,
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class App {}

Solution

  • When placing a swiper-container inside a mat-grid-tile within an Angular Material mat-grid-list, the swiper component doesn’t display correctly by default. The slides either don't take up the full space, or they have layout issues.

    To fix this, add width: 100% to the swiper-container. This will make it take up the full width of the mat-grid-tile, allowing the swiper to render and distribute the slides correctly.

    swiper-container { width: 100%; }