Hi there,
I am implamenting a calendar in my app and I want to add option to swite to next/prev month
So I was thinking to do it with the slider element.
I will need to make the slider Infinite.
So on creation I will have just 3 slides:
- prev wonth
- current wonth
- next wonth
And when I slide to next month I need to create a new slide for the next-next month
If I slide from current wonth to prev I need to create a new slide for the prev-prev month
And so on.
What is the best way to do that?
Thank you.
I wanted to do the same. The best way I found is to use a range of slides, and put my current index in the middle.
<ion-slides #slides
[options]="slidesOptions"
(ionSlidesDidLoad)="ionSlidesDidLoad()"
(ionSlideNextEnd)="ionSlideNextEnd()"
(ionSlidePrevEnd)="ionSlidePrevEnd()">
<ion-slide *ngFor="let number of slidesNumber; index as i;">
<app-month *ngIf="i === slideIndex" [date]="initialDate"></app-month>
</ion-slide>
</ion-slides>
Using this way you are only loading the current month (for performance reasons).
import {ChangeDetectionStrategy, Component, OnInit, ViewChild} from '@angular/core';
import {IonSlides} from '@ionic/angular';
import '../../interfaces/DatePrototype';
@Component({
selector: 'app-calendar',
templateUrl: './calendar.page.html',
styleUrls: ['./calendar.page.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CalendarPage implements OnInit {
static MONTHS_NUMBER = 24;
static MONTHS_INITIAL_INDEX = 12;
@ViewChild('slides') slides: IonSlides;
public slidesNumber: Array<number>;
public slideIndex: number;
public slideLoaded: boolean;
public initialDate: Date;
public slidesOptions: Object = {
initialSlide: CalendarPage.MONTHS_INITIAL_INDEX,
effect: 'flip'
};
constructor() { }
ngOnInit() {
this.slidesNumber = Array.from({length: CalendarPage.MONTHS_NUMBER}, (v, k) => k);
this.slideIndex = CalendarPage.MONTHS_INITIAL_INDEX;
this.slideLoaded = false;
this.initialDate = new Date();
}
public ionSlidesDidLoad(): void {
this.slideLoaded = true;
}
public ionSlideNextEnd() {
if (! this.slideLoaded) {
return;
}
this.slides.getActiveIndex().then((index: number) => {
this.slideIndex = index;
this.initialDate.addMonths(1);
});
}
public ionSlidePrevEnd() {
if (! this.slideLoaded) {
return;
}
this.slides.getActiveIndex().then((index: number) => {
this.slideIndex = index;
this.initialDate.removeMonths(1);
});
}
}
Please note that slideLoaded
variable is very important. If you do not checkit it, initialSlide
will trigger an event and call ionSlideNextEnd()
.