It is necessary to show all the elements of the array in turn, if there is a click on "NEXT" and the index "0" is obtained, currently nothing is displayed if the index is "0", and clicking sometimes does not work. How to make a slider that shows all the elements of the array, even if the index is "0" and the click always works?
import { Component } from '@angular/core';
@Component({
selector: 'app-my',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class CalendarDay {
d = new Date();
monthNames = ["1January", "2February", "3March", "4April", "5May", "6June",
"7July", "8August", "9September", "10October", "11November", "12December"];
index: number = 1
i: number = -1;
shMonth = this.monthNames[0];
next() {
this.shMonth = this.monthNames[this.index ];
if (this.index === 12) {
this.index = 0;
}
}
prev() {
this.shMonth = this.monthNames[this.index this.i];
this.index--;
if (this.index === 0) { this.index = 12 }
if (this.index === -1) { this.index = 12 }
}
}
<h1>{{shMonth}}</h1>
<p>index:{{ index }}</p>
<button (click)="next()">NEXT</button>
<button (click)="prev()">PREV</button>
CodePudding user response:
An array goes from 0 to array.length-1. Your prev and next should be like
next()
{
this.index=(this.index 1);
this.shMonth = this.monthNames[this.index];
}
prev()
{
this.index=(this.index 11);
this.shMonth = this.monthNames[this.index];
}
See that you use the "reminder operator" -get the remainder of the division-, e.g. 13=1. This is the reason you add 11 (12-1) in the prev function