-1

This is the function defined in MainService.ts, it can change the color set in badgesColorSet ,I have 3 colors defined in the json config already and i want these 3 colors to change everytime I open the website lets it is red then i refresh the page it should be green and then i refresh again it should be blue. so is this function correct and should i use for loop ?and I think i need to divide it by something so it increments and goes from 0 ,1 ,2 as index?

getIteriateColor(){
        //gets  color out of color set from turnkey.config file for badges
    let  badgesColorSet = 0; badgesColorSet < Array.length; badgesColorSet++;
        console.log(badgesColorSet);
        return badgesColorSet;

the colors are defined in turnkey-config.json

"badgesColorSet":["#ffff00","#f51307","#0cc902"],

this code is in the mainservice to define the background color of the material badge

badge: {bg: this.getNextColor() , fg: 'white' , title: moduleBadge},

enter image description here

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • I think you should a Math.random or something and deduce a color based on the random value – mak15 Mar 24 '22 at 07:20
  • If you definitely want it to go to the next color on a refresh you are going to have to remember what color you were on before. How are you doing that? (e.g. setting a cookie??). – A Haworth Mar 24 '22 at 07:24
  • @mak15 no i dont want colors to appear randomly i want the colors to go sequentially iteirate "badgesColorSet":["#ffff00","#f51307","#0cc902"], –  Mar 24 '22 at 07:27
  • @AHaworth i dont want colors to appear randomly i want the colors to go sequentially iteirate "badgesColorSet":["#ffff00","#f51307","#0cc902"] –  Mar 24 '22 at 07:28
  • Yes, which is why I asked how are you going to remember what color was shown last time? Are you using a cookie? – A Haworth Mar 24 '22 at 07:45
  • @AHaworth i found the answer Thank you soo much for your help ! –  Mar 24 '22 at 09:10

5 Answers5

0

If you want to "make something" when you refresh, you use localstorage I imagine you can use some like

  color
  badgesColorSet=["#ffff00","#f51307","#0cc902"]
  ngOnInit(){
    let index=localStorage.getItem('indexColor')!=undefined?
                       +localStorage.getItem('indexColor'): -1
    index=(index+1)%3;
    localStorage.setItem('indexColor',''+index)
    this.color=this.badgesColorSet[index]
    
  }

See that at first, if not exist localstorage.getItem('indexColor') (that's undefined) You makes index=0 and store "0", the next time you store "1","2","0","1","2"... -localStorage only admit "strings" it's because you use ''+index to convert to string and +localStorage.getItem('indexColor') to conver to number

The use of ìndex=(index+1)%3 makes that the value of index becomes 0,1,2,0,1,2,0,1,2...

NOTE: You can use also sesionStorage (Just replace in code localstorage by sessionStorage)

Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • Is there a way for it not to be on localstorage and actually this is the closest answer till now since the site is run on servers and on runtime so possibly if there is something else other than localstorage thank you !! –  Mar 24 '22 at 07:46
  • Always you want that "after refresh" makes something with an old value you need "store" a variable in client using localstore, cookies, [session](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) or indexdbs -perhafps you're looking for session- (well, if you has a typical app with users and depends of users you can store in the server in some field of the dbs). Other option can be use a `Math.floor(Math.random()*3)` to get a random number between 0,1 or 2. but you can not sure the order. Math random can give you two 0s or a 1 and 0) in two differents calls – Eliseo Mar 24 '22 at 08:37
  • Is there a reason you store every value ever used in local storage rather than just store the last used color in a cookie? – A Haworth Mar 24 '22 at 09:15
  • read this [SO](https://stackoverflow.com/questions/3220660/local-storage-vs-cookies). they explain better than me. NOTE: Really I'm more used to use localstore, so it's not a good reason – Eliseo Mar 24 '22 at 09:17
0

I think the best way is to use [ngClass] and condition by pointing to the css classes that you have predefined with those colors.

Basuh
  • 31
  • 4
0

In Component:

interface Link {
  label: string;
  route: string;
  icon: string;
}

links: Link[] = [ // your links ]

Inside Template:

<nav>
  <a *ngFor="let link of links; let odd = odd" [href]="link.route" [class.odd]="odd">{{link.label}}</a>
</nav>
Shafi
  • 1
  • 1
  • 2
0

Assuming getNextColor() calls getIteriateColor() to get the next color.

On getIteriateColor() let's loop through "badgesColorSet":["#ffff00","#f51307","#0cc902"] and starting again from [0] when iterate reaches [2].

To remember what color was last used we should store it somewhere on the client where the state remains (e.g localStorage), that way we know what color to choose next.

@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]
        );
      }
    }
  }
}

Working example: https://stackblitz.com/edit/angular-ivy-mw7s49?file=src%2Fapp%2Fapp.component.ts

Or for backend something similar except without 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},
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33
  • Thank you soo much ,i used the backend version it is so helpful and it worked it changed the color whenever i refreshed but and now i have a small quick question when i tried adding more colors to the array the colors are not changing lets say red and green and doesnt change whenever i refresh the page but and i want to use consloe.log('') or some other method to test it out –  Mar 24 '22 at 09:09
  • if you help me with this forsure i will donate money to you good sir ! This is the code for the material badge that needs to be fixed, it should already have the index saved starting from zero and increments and it shouldnt use indexOf or color index and the property should be changed to number instead of string so it doesnt make loops to find the index so the code is cleaner and faster –  Mar 24 '22 at 10:26
  • Length of the array doesn't matter, add however many colors you want as you want. Basically what happens is when you call `getIteriateColor()` then `badgesColorSelected` will be set to a new color from `badgesColorSet[]`. I updated the last example slightly. – Joosep Parts Mar 24 '22 at 10:30
  • 1
    yes it worked but i mean is there any other way to do it to make it more cleaner or simpler , for example if we use foreach or something else and i will send the donation as soon as possible thank you ! –  Mar 24 '22 at 10:46
  • Looks simple and clean for me. If you have better ideas using `forEach` be my guest and show us your version. It's always possible to refactor. There is no one definitive good version. – Joosep Parts Mar 24 '22 at 11:08
  • 1
    yes it is amazing work sir but if its possible to make the functioanlity work without indexof i would be glad thank you so much ! –  Mar 24 '22 at 11:10
0

this is for the function i did some change to Joosep.P thanks to him .

getIteriateColor() {

    if (!this.badgesColorSelected) {
      this.badgesColorSelected = 0;
    } else {
      const colorIndex = this.badgesColorSelected;
      if (colorIndex + 1 > this.badgesColorSet.length - 1) {
        this.badgesColorSelected = this.badgesColorSet[0];
      } else {
        this.badgesColorSelected = this.badgesColorSet[colorIndex + 1];
      }
    }
    console.log('current color is: ', this.badgesColorSelected);
    
    return this.badgesColorSelected;
}
}

this is for the config

 "badgesColorSet":["#f51307","#0cc902","#ffff00","#03fcf8","#03fcb1"],