Setting Parameters in Ionic 7 Swiper 11 using Typescript

Below are the codes that I have written. My goal is to use a script to configure the parameters of the swiper slider.

<swiper-container [options]="recentPostSliderOpts" class="discover-top-banner">
  <swiper-slide *ngFor="let toplatestpost of toplatestposts">
     <!-- Some Codes Here Cut Short -->
  </swiper-slide>
</swiper-container>

Here is my TypeScript code snippet.

import { Swiper, SwiperOptions } from 'swiper/types';

recentPostSliderOpts: SwiperOptions = {
  slidesPerView: 3,
}

The [options] attribute is not functioning as expected based on the Ionic Framework guide available at https://ionicframework.com/docs/angular/slides. It worked fine with Swiper 9 but seems to be causing issues with Swiper 11. I have referred to the official documentation on the SwiperJS website but could not find a solution. I also attempted using [config] without success.

If anyone has some insights or suggestions, I would greatly appreciate your help!

Answer №1

To achieve this, you must:

1 - Start by creating a directive for the swiper and utilize a template variable to store the current swiper reference

<swiper-container appSwiper #swiperRef [config]="recentPostSliderOpts" class="discover-top-banner">
    <swiper-slide *ngFor="let toplatestpost of toplatestposts">
         <!-- Some Codes Here Cut Short -->
    </swiper-slide>
</swiper-container>

2 - In the typescript file, define the configuration you desire and store the swiper reference in a variable to monitor events.

swiper!: Swiper;
@ViewChild('swiperRef') swiperRef!: ElementRef<SwiperContainer>;

recentPostSliderOpts: SwiperOptions = {
  spaceBetween: 10,
  navigation: true,
  slidesPerView: 1.2,
}

ionViewDidEnter() {
  this.swiper = this.swiperRef?.nativeElement.swiper;

  this.swiper.on('slideChange', (swiper) => {
    console.log('slide changed:', swiper.realIndex);
  });
}

3 - Develop the directive

import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core';
import { SwiperContainer } from 'swiper/element';
import { SwiperOptions } from 'swiper/types';

@Directive({
  selector: '[appSwiper]',
  standalone: true
})

export class SwiperDirective implements AfterViewInit {

  @Input() config?: SwiperOptions;

  constructor(private el: ElementRef<SwiperContainer>) { }

  ngAfterViewInit(): void {
    Object.assign(this.el.nativeElement, this.config);

    this.el.nativeElement.initialize();
  }

}

4 - Ensure to include the SwiperDirective in your module imports array

5 - Also add schemas: [CUSTOM_ELEMENTS_SCHEMA] in your module to prevent any build errors

6 - Invoke the register function at a single location in your project, preferably in the app.module.ts file

import { register } from 'swiper/element/bundle';
register();

Now, everything should be functioning smoothly. Best of luck! 😉

Answer №2

While this answer provides a solution, it fails to include the crucial init="false" attribute on the swiper container. Failing to do so may lead to the error: "Cannot read properties of null (reading 'remove')". For more information on virtual slides, visit:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message ...

How can one define a getter within an interface?

One of my classes is structured like this (only showing a portion here): export class LinkedListNode<t> extends windward.WrObject implements ILinkedListNode<t> { public get next(): LinkedListNode<t> { return this._next === thi ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

Unable to modify the border-radius property of Material UI DatePicker

I'm having difficulties setting rounded borders for my DatePicker component from @mui/x-date-pickers and Material UI V5. Here is the intended look I am aiming for: https://i.stack.imgur.com/c1T8b.png I've tried using styled components from Mat ...

Challenges with promises in Angular Firebase Realtime DB

Having some difficulties with Angular and Firebase Realtime DB. In my database service, I created a function like this: getAllProject() { return firebase.database().ref('project').once('value').then((snapshot) => { if (snapsh ...

Repeating percentages displayed in a progress bar

I created a responsive progress bar, but the progress values are repeating. I only want the central value to be displayed. Any suggestions on how to fix this issue? DEMO <div id="tab1"> <dx-data-grid class="tableTask" [dataSource]="datas" ...

Unable to install android application due to duplicated code

I created a hybrid app for Android using Ionic v1 and Angular 1 which is currently running smoothly. I have already uploaded it to the Play Store. Now, I have copied the same code to create a new app, changed the name and package path. However, I am facin ...

Which is more efficient: Using TypeScript's Object.assign() or creating a new object?

Seeking advice on two different approaches to implementing a method with a constant. Unsure about the better option. Can someone provide guidance? Thank you! Approach 1: Declaring the constant outside of the class, causing it to be invoked only once but r ...

How can I handle the different data type returned by ReactDom.render?

My main focus is on rendering Markdown. Additionally, I also need to parse HTML which is passed as a string. In this scenario, children represents the HTML passed as a string, while isParseRequired indicates if parsing is needed. import cx from 'clas ...

Tips on utilizing AWS IAM within a Node.js application when running a Fargate scheduled task

As a student, I am attempting to create a scheduled task in nodejs using typescript. The task involves accessing S3, fetching an object, and then performing some operations on it. My main challenge at the moment is figuring out how to load the credentials ...

Issue encountered when attempting to deploy webpack react app to AWS S3 bucket

Hello, I've been using webpack to bundle my production code and everything works fine in the development environment. However, when I deploy to AWS S3 and try to access the website, I get a strange error: Uncaught ReferenceError: $RefreshReg$ is not d ...

Tips for optimizing data loading in Angular by pre-loading data to prevent unnecessary Firebase reads

Issue: One specific part of my web application is responsible for fetching a large amount of data from Firebase Firestore whenever a user visits that section. This results in hundreds of thousands of unnecessary reads to my Firestore database. Inquiry: Ho ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...

Nextjs 13 brings exciting new features, one of which is the ability to call getStatic

I am working on a Next.js 13 application where I have organized my files in the 'app' directory instead of the usual 'pages'. All pages are statically generated during build time and data is fetched from an external API. https://i.sstat ...

What is the process for exporting dynamic paths with the NextJS app using static methods

My webpage is located within the directory src/app/c/patient/[id]/page.tsx. Everything is functioning correctly when deployed, but I'm trying to export it to a js bundle for use with the Capacitor Android/iOS app. However, I encountered the following ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Inheritance-based generic type inference in Typescript

Take a look at this piece of code: class A<T> { t?: T; } interface B {} class C implements A<B> {} function f<T1 extends A<T2>, T2>(a: T1): T2 | undefined { return a.t; } const result = f(new C()); const result2 = f(new A<B> ...

The formBuilder controls' setValue() and patchValue() methods are not functional when called within a method of a Cordova plugin

In developing my Ionic tabs app, I have integrated the cordova-plugin-datepicker and utilized Angular Material to design the form fields. One issue I encountered is setting the text input's value with the date obtained from the plugin’s calendar in ...