How to Dynamically Update SwiperJs Language Direction (RTL / LTR) in Angular?

Discussão em 'Angular' iniciado por Asmaa Mahmoud, Junho 18, 2025.

  1. Problem


    I'm using Swiper Element in an Angular component and I want to dynamically update the swiper's direction based on the current language ('ar' for RTL, 'en' for LTR) using a LangService.

    The swiper works fine initially, but when the language is changed at runtime, the Swiper layout breaks (e.g. wrong direction, wrong navigation, broken layout).

    Code


    swiper.component.html

    <swiper-container #swiperContainer init="false" class="h-100">
    @for (product of [].constructor(9); track $index) {
    <swiper-slide>
    <app-small-product-card />
    </swiper-slide>
    }
    </swiper-container>


    swiper.component.ts

    @Component({
    selector: 'app-mini-product-swiper',
    ...
    })
    export class MiniProductSwiperComponent {
    lang = inject(LangService).currentLang;

    @Input() swiperClass = '';
    @Input() swiperBreakpoints = { ... };

    @ViewChild('swiperContainer') swiperContainer!: ElementRef;

    constructor() {
    effect(() => {
    const lang = this.lang();
    if (lang === 'ar') {
    // update swiper direction to rtl
    } else {
    // update swiper direction to ltr
    }
    });
    }

    platformId = inject(PLATFORM_ID);

    ngOnInit(): void {
    // register Swiper Element
    register();
    }

    ngAfterViewInit(): void {
    if (isPlatformBrowser(this.platformId)) {
    this.assignSwiperParams();
    }
    }

    assignSwiperParams() {
    const swiperElement = this.swiperContainer.nativeElement;
    const swiperParams: SwiperOptions = {
    modules: [Navigation, Autoplay],
    slidesPerView: 1,
    spaceBetween: 16,
    speed: 500,
    loop: false,
    grabCursor: true,
    navigation: {
    nextEl: `.${this.swiperClass}-button-next`,
    prevEl: `.${this.swiperClass}-button-prev`,
    },
    autoplay: {
    delay: 2500,
    disableOnInteraction: true,
    },
    breakpoints: this.swiperBreakpoints,
    };

    // now we need to assign all parameters to Swiper element
    Object.assign(swiperElement!!, swiperParams);

    // and now initialize it
    swiperElement?.initialize();
    }
    }

    Question


    How can I update the Swiper direction ('rtl' or 'ltr') dynamically after the language is changed?

    • Do I need to destroy and re-initialize the Swiper?
    • Is there a way to re-assign the direction param and re-render without breaking the layout?
    • What’s the recommended approach when using in Angular?

    Any help or working example would be greatly appreciated. Thank you!
    ​

    Continue reading...

Compartilhe esta Página