When getNextColor()
is called, it invokes getIteriateColor()
to fetch the next color.
Within getIteriateColor()
, we cycle through the colors in
"badgesColorSet":["#ffff00","#f51307","#0cc902"]
, restarting from index
[0]
once we reach index
[2]
.
To keep track of the last used color, we need to store it on the client side where the state persists (e.g., localStorage), ensuring that the next color is chosen correctly.
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
badgesColorSet = ['#ffff00', '#f51307', '#0cc902'];
badgesColorSelected: string;
constructor() {
this.getIteriateColor();
}
getIteriateColor() {
// if there is no color in localStorage, set the first color
if (!localStorage.getItem('badgesColorSelected')) {
localStorage.setItem('badgesColorSelected', this.badgesColorSet[0]);
} else {
// if there is color, select the next color
const storageColor = localStorage.getItem('badgesColorSelected');
const colorIndex = this.badgesColorSet.indexOf(storageColor);
if (colorIndex + 1 > this.badgesColorSet.length - 1) {
this.badgesColorSelected = this.badgesColorSet[0];
localStorage.setItem('badgesColorSelected', this.badgesColorSet[0]);
} else {
this.badgesColorSelected = this.badgesColorSet[colorIndex + 1];
localStorage.setItem('badgesColorSelected',this.badgesColorSet[colorIndex + 1]
);
}
}
}
}
You can find a working example here: https://stackblitz.com/edit/angular-ivy-mw7s49?file=src%2Fapp%2Fapp.component.ts
For backend implementation, a similar approach can be taken without using localStorage.
badgesColorSet: string[] = ['#ffff00', '#f51307', '#0cc902'];
badgesColorSelected: string;
getIteriateColor() {
if (!this.badgesColorSelected) {
this.badgesColorSelected = this.badgesColorSet[0];
} else {
let nextColorIndex = 0;
for (let i = 0; i < this.badgesColorSet.length; i++) {
if (this.badgesColorSet[i] === this.badgesColorSelected) {
if (i <= this.badgesColorSet.length - 2) {
nextColorIndex = i + 1;
break;
}
}
}
this.badgesColorSelected = this.badgesColorSet[nextColorIndex];
}
console.log('current color is: ', this.badgesColorSelected);
}
badge: {bg: badgesColorSelected , fg: 'white' , title: moduleBadge},