Creating Dynamic Ionic Slides with Additional Slides Inserted Before and After

Hello, I am currently using ngFor to generate a set of 3 slides with the intention of starting in the middle so that I can smoothly slide left or right from the beginning.

When I slide to the right, I can easily detect when the end is reached and add another slide to the looping array.

However, I encounter an issue when trying to add a slide to the beginning. If I try to use methods like array.unshift() or spread to insert an item at the beginning, the view jumps to position 0 and disrupts the sliding experience.

The code snippet below does somewhat work but it causes a slide animation back to index 1.


slide = [0, 1, 2] //example for looping
slideChanged(event) {
    if(this.slides.isBeginning()){
        this.slide = [this.slide[0]-1, ...this.slide];
        this.slides.update();
        this.slides.slideTo(1)
    }
}

<ion-slides [initialSlide]="1" (ionSlideDidChange)="slideChanged($event)">
    <ion-slide *ngFor="let item of slide">
        <h1>Slide {{item}}</h1>
    </ion-slide>
</ion-slides>

I would greatly appreciate any assistance or suggestions on how to solve this issue!

Answer №1

To achieve this functionality, utilize the ionSlideNextEnd and ionSlidePrevEnd events from the Slides component. Refer to this live example for a working demonstration.

Implementation Example

<ion-header>
  <ion-navbar>
    <ion-title>Dynamic Slides Demo</ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
    <ion-slides #slider (ionSlideNextEnd)="loadNext()" (ionSlidePrevEnd)="loadPrev()" [initialSlide]="1">
        <ion-slide *ngFor="let n of numbers">
            <h2>Current slide: {{n}}</h2>
        </ion-slide>
    </ion-slides>
</ion-content>

Component Logic

@Component({...})
export class HomePage {
    @ViewChild('slider') private slider: Slides;

    numbers = [0,1,2];
    firstLoad = true;

    constructor() {}

    loadPrev() {
        console.log('Prev');
        let newIndex = this.slider.getActiveIndex();

        newIndex++;
        this.numbers.unshift(this.numbers[0] - 1);
        this.numbers.pop();

        // Temporary solution to maintain functionality which affects animation
        this.slider.slideTo(newIndex, 0, false);

        console.log(`New status: ${this.numbers}`);
    }

    loadNext() {
        if(this.firstLoad) {
          // Prevent initial movement from altering slides
          this.firstLoad = false;
          return;
        }

        console.log('Next');
        let newIndex = this.slider.getActiveIndex();

        newIndex--;
        this.numbers.push(this.numbers[this.numbers.length - 1] + 1);
        this.numbers.shift();

        // Temporary workaround to ensure functionality without animation disruption
        this.slider.slideTo(newIndex, 0, false);

        console.log(`New status: ${this.numbers}`);
    }
}

Answer №2

Seeking a solution for making this work on Ionic 4? With some minor adjustments to the typescript component, you can get it up and running.

Check out the modified code that functions in IONIC 4:

ionSlideNextEnd(){
  if(this.firstLoad) {
    // Prevent slides from being modified during initial movement
    this.firstLoad = false;
    return;
  }

  console.log('Next');
  this.daySlider.getActiveIndex().then(idx=>{
      let newIndex=idx
      console.log(newIndex)
      newIndex--;
      this.numbers.push(this.numbers[this.numbers.length - 1] + 1);
      this.numbers.shift();

      // Implementation to ensure functionality: interrupts animation
      this.daySlider.slideTo(newIndex, 0, false);

      console.log(`Updated status: ${this.numbers}`);
  });


}

ionSlidePrevEnd(){
console.log('Previous');
this.daySlider.getActiveIndex().then(idx=>{
    let newIndex=idx
    console.log(newIndex)
    newIndex++;
    this.numbers.unshift(this.numbers[0] - 1);
    this.numbers.pop();

    // Implementation to ensure functionality: interrupts animation
    this.daySlider.slideTo(newIndex, 0, false);

    console.log(`Updated status: ${this.numbers}`);
});
}

If you prefer a simpler approach, consider eliminating the getter for Active Index and utilize the following code for Ionic 4:

ionSlideNextEnd(){
    if(this.firstLoad) {
        this.firstLoad = false;
        return;
    }else{
        this.numbers.push(this.numbers[this.numbers.length - 1] + 1);
        this.numbers.shift();

        // Implementation to ensure functionality: interrupts animation
        this.daySlider.slideTo(1,0,false);
        this.monthViewData.selectedTime=new Date(this.monthViewData.selectedTime.setDate(this.monthViewData.selectedTime.getDate()+1));
        this.eventSource = this.tmp_events.filter((item)=>{
            if(item.startTime >= this.monthViewData.selectedTime.setHours(0,0,0,0) && item.endTime < this.monthViewData.selectedTime.getTime()){
                return item;
            }
        });
    }

}

ionSlidePrevEnd(){

    this.numbers.unshift(this.numbers[0] - 1);
    this.numbers.pop();

    this.daySlider.slideTo(1,0,false);
    this.monthViewData.selectedTime=new Date(this.monthViewData.selectedTime.setDate(this.monthViewData.selectedTime.getDate()-1));
    this.eventSource = this.tmp_events.filter((item)=>{
        if(item.startTime >= this.monthViewData.selectedTime.setHours(0,0,0,0) && item.endTime <= this.monthViewData.selectedTime.getTime()){
            return item;
        }
    });
}

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

TypeScript purity - "The variable exports is not defined"

I encountered an issue with my simple client-server TypeScript application where every import statement in my client.ts file triggers a ReferenceError: exports is not defined error in the browser after loading the HTML. Here is the project structure: root ...

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

Can a single data type be utilized in a function that has multiple parameters?

Suppose I have the following functions: add(x : number, y : number) subtract(x : number, y : number) Is there a way to simplify it like this? type common = x : number, y : number add<common>() This would prevent me from having to repeatedly define ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

Restricted inclusive collection utilizing embedded identifier

Attempting to segregate a discriminated union array into separate arrays of its union types has presented some challenges. I came across this particular question that provides generic discriminators. Unfortunately, the dataset I am working with doesn&apos ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

Angular 6 Checkbox Selector - Filtering Made Easy

How can I filter a list of JSON objects (Products) by the 'category' variable using checkboxes? An example product object is shown below: { 'bikeId': 6, 'bikeName': 'Kids blue bike', 'bikeCode': ...

Troubleshooting Angular 6: Issues with Route Guards not functioning as expected

Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id to a page-not-found error message if not already logged in, but encountering some issues. Below are t ...

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

Is there a way to use an Angular interceptor to intercept and modify static files like .html files? I would like to change the lang

While researching Angular intercepting, I stumbled upon this helpful documentation: here. My goal is to intercept HTML using an Angular interceptor in order to modify the HTML file before it's displayed in the browser. Trying to accomplish this on the ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...

Unable to view cross domain cookies within the browser's development tools

I am currently working on a web application that has an Angular front end running on http://localhost:4200 and a NodeJs backend running on http://localhost:3000. When a user successfully logs in, a cookie is set from the backend containing a token. However ...

What is the best way to pre-fetch data using axios in Vue?

My app requires offline functionality for drivers operating in remote areas with limited internet access. To address this, I aim to pre-download all necessary data using Axios requests when an internet connection is available. This way, the app can retriev ...

Are there any more efficient methods to retrieve an object from an arrow function in TypeScript?

Trying to retrieve an object from an arrow function is posing a challenge for me, especially with the following function f: myMethod(f: data => { return { someField: data.something }; }); I am aware that for simple types, you can condense the arrow ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Initial request in the sequence is a conditional request

Currently, I am attempting to make a request in rxjs that is conditional based on whether or not the user has uploaded a file. If a file has been uploaded, I need to attach it to the user object before sending it off, and then proceed to patch the user aft ...

Variable type linked to interface content type

Is it possible to link two fields of an interface together? I have the following interface: export interface IContractKpi { type: 'shipmentVolumes' | 'transitTime' | 'invoices'; visible: boolean; content: IKpiContent; } ...

Encountering an error when implementing a router object within a TypeScript class in a Node.js environment

I have a Node.js service written in TypeScript. I am currently working on implementing a separate routing layer within the application. In my app.js file, I have the following code: let IndividualRoute= require('./routing/IndividualRoute'); app ...