I have an angular component that needs to cycle through an array. Below, I have an array and a global variable called currentAlbum
which will hold the value of the album currently being viewed.
The below works, but with some odd behaviour.
Question 1
Firstly, even though it cycles through correctly, i added console logs to make sure the if statement worked correctly and that it'll begin from the beginning again after reaching the end. The 'currentAlbum' console log will always be one behind of where it appears on screen. Any obvious reason for that? For example, on screen album 3 will be present, the console log will say album 2.
Question 2
I also have 5 buttons on the screen, each one, when clicked will show the selected album. This is a simple this.currentAlbum = selectedValue
(selectedValue being received from the HTML click). However, when doing this, the timer continues to run. If the timer is five seconds and I click a carousel button at 4 seconds, the new album will show for 1 second before changing to the next. Is there a way to reset this value? (I've also read that setTimeout is a better approach...?)
currentAlbum: number = 1;
albumsArray = [
{ title: "Album 1", index: 1 },
{ title: "Album 2", index: 2 },
{ title: "Album 3", index: 3 },
{ title: "Album 4", index: 4 },
{ title: "Album 5", index: 5 },
]
---------
ngOnInit() {
this.theCarousel();
}
theCarousel() {
setInterval(() => {
if (this.albums == 5){
this.currentAlbum = 1;
console.log('this is album 5)
} else {
this.currentAlbum++;
console.log('this is not album 5)
}
}, 2000);
}