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

What is the best method for sorting through observable data pulled from an API?

public data$: Observable<any[]>; ngOnInit(): void { this.data$ = this.InventoryService.getAllProducts(); } searchProducts(event: any) { let searchTerm: string = event.target.value; console.log(searchTerm); this.data$.pipe( ...

Updating displayed content based on orientation switch

Two components, A and B, are displayed simultaneously - A on the left and B on the right - when the device is in landscape mode. In portrait mode, either A or B will be displayed based on user selection. The components can transition from A to B and vice v ...

Incorporate service providers into models with Ionic3/Angular4

I am seeking feedback from individuals with more experience than me to determine if my approach is correct. I am currently working on an Ionic3-Angular app that involves a CRUD functionality for "Clientes". From what I have researched, the recommended st ...

Angular 4: Triggering Scroll Event when Select Dropdown Reaches End

I am attempting to trigger a Scroll Event within the component class when the end of the dropdown list is reached. I have a large list and initially only load the first 30 records in ngOnInit(). As the user scrolls down, I want to update the dropdown list ...

Creating a bullet list from a dynamically parsed object: step-by-step guide

Here is my JSON string foo_json_string: [{"foo_name":"foo_value"},{"foo_name1":"foo_value1"}] I am trying to parse it and display it as an HTML list. This is the method I attempted: <ul> <li v-for=" ...

Performing Iterations in Angular 2 with Immutable.js (utilizing the *ngFor directive)

Struggling with Angular 2 and Immutable JS - having issues with a simple for-loop in my template. Tried both old and new syntax without success. <div *ngFor='#filter of filterArray' class='filter-row'> <div class='row-t ...

What is the method for adjusting the spacing between binding tags within HTML code formatting specifically for TypeScript elements in IntelliJ?

My Angular binding currently defaults to <h1>{{typeScriptVar}}</h1>, but I would like it to be set as <h1>{{ typeScriptVar }}</h1> when I use the format code shortcut in InteliJ. Can anyone assist me with this issue? I have resear ...

Element without style

In my app, I have implemented numerous material design components, but there are two input elements for which I would like to customize the style and remove the default material design look. Is there a way to eliminate the CSS styling from an <input ma ...

The Angular application's "wait" dialog fails to appear

I'm currently setting up a dialog that includes a mat-spinner while the page data is loading in an Angular v14 project. Instead of using a basic spinner, I opted for a dialog because I need to pass some additional information within it. However, I&apo ...

Can you explain the distinction between an optional field and a union?

Is there a significant distinction between the following structures: { ok: boolean; } | { ok: boolean; error: any; } and: { ok: boolean; error?: any; } I have observed variance in the inferred types of frontend methods' return ou ...

The header Origin:file:// from the Ionic native app is generating issues

While working on my simple Todo app in Ionic 1, I encountered an issue with the Origin header, specifically related to CORS. Running ionic serve works perfectly fine in the browser and allows me to make requests to my REST API on Apache (Tomcat). Howev ...

What is the best way to organize a material table with favorites prioritized at the top?

My goal was to customize the sorting of a mat-table in Angular, ensuring that the "favorite" items always appear at the top of the table. I aimed for the favorite items to maintain their position as the first items in the table regardless of any other sor ...

What is the process of deploying Angular Server Side Rendering (SSR) build files to Azure Web App service using FileZilla FTP?

I'm currently working on Angular SSR and utilizing the Angular official sample project for testing purposes. Steps for building the Angular SSR project: Execute npm run build:ssr This will automatically generate the dist folder, which contains both ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

Utilizing req.session in an Express application with Angular (written in TypeScript) when deploying the backend and frontend separately on Heroku

I'm currently facing an issue where I am unable to access req.session from my Express app in Angular. Both the backend and frontend are deployed separately on Heroku. I have already configured CORS to handle HTTP requests from Angular to my Express ap ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite. Now, I am interested in using TypeScript ...

Encountering the error message "Received interpolation ({{}}) when an expression was expected" is a common issue when trying to interpolate tag attribute values within an ngFor loop

I've been working with a Devextreme's Datatable and my goal is to dynamically configure the table using a columns configuration array. The plan is to loop through this array using an ngFor and set column tags properties dynamically. Now, the bi ...

Importing and declaring child components in Angular testing with Karma, Jasmine, and TestBed is essential for comprehensive component testing. This ensures all

Challenge Description: When writing unit tests using karma/jasmine for an angular component that utilizes other angular components, there is a need to recursively import all components included in child components into the testbed configuration. Is there a ...

Steps for numbering a list with multiple ngfors within a div using Angular

How can I ensure that multiple ngfors output an undefined number of results listed in a specific format with incremental numbering? EXPECTED OUTPUT: 1. Object 1 News: Object 1 Stuff 2. Object 1 News: Object 1 Stuff 3. Object 1 News: Object 1 Stuff ...