Menu Navigation: Sequentially Colored Badges for Navigation Items

Within the MainService.ts file, there is a function that can alter the color set in badgesColorSet. The json config already defines 3 colors and the goal is for these colors to change each time the website is refreshed - for example, changing from red to green to blue. Is this function correct? Should a for loop be used? It seems like there should be a division involved to increment the colors from index 0 to 1 to 2.

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 color options are specified in the turnkey-config.json file:

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

This code in the mainservice is responsible for defining the background color of the material badge:

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

https://i.sstatic.net/syJl0.png

Answer №1

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},

Answer №2

In my opinion, the most effective approach is to utilize [ngClass] and set conditions based on the predefined CSS classes that correspond to the desired colors.

Answer №3

Within the Component:

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

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

Within the Template:

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

Answer №4

If you're looking to add a special touch every time a page refreshes, consider using localStorage. Here's an example:

  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]
    
  }

If the initial value of localstorage.getItem('indexColor') is undefined, the script sets index to 0 and stores "0". Subsequent iterations will store "1", "2", "0", "1", "2"... as localStorage only accepts "strings". To convert to a string, use ''+index, and to convert to a number, use +localStorage.getItem('indexColor').

By using índex=(index+1)%3, the index value will cycle through 0, 1, 2, 0, 1, 2, and so on.

NOTE: Alternatively, you can also utilize sessionStorage by replacing localStorage with sessionStorage in the code.

Answer №5

Modifications were made to Joosep.P's function, thanks to his input.

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 section pertains to configuration settings

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

IE having issues with selecting all options button in jQuery, but it is functioning correctly in Firefox

In one part of my cgi code, I create the following: my $PARAMETER_HTML .= "<select name='parameters' id='parameters' size='10' multiple='multiple'>"; foreach my $values (sort @PARA_VALUES) { $PARAMETER_HTM ...

Identify the index of a list item using a custom list created from buttons

When dealing with a dynamically built list like this: <ul id="shortcuts"> <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li> <li><input type="checkbox" value ...

I wonder, who is the one executing the function?

In my application, I have encountered an unusual issue. Within my controller, I have two functions - one to add a tab, and one to remove a tab. Below is the code snippet: $scope.createTab = function(){ $scope.addTab("New Tab",50,0); co ...

React can easily incorporate CSS from multiple components

I'm experiencing a CSS import issue in my React project. I have a "Home" page that imports Home.css and a "Hero" page that imports Hero.css. Strangely, the styles from Hero.css are being applied to every page in the application without me explicitly d ...

How can I generate an Xpath for the given element?

I am trying to find the Xpath for the specific name (I1888 - Child 1.1) without using the contains function. Currently, I am using the following xpath: "//span[contains(@class,'TreeTitleRed')][contains(.,'Child 1.1')]", but I would like ...

Issue with Jhipster4 when trying to generate an Angular 2 app

After utilizing jhipster4 to create my application, I noticed it consists of a client side and a server side. However, when running ./mvnw from the application's root directory, only the server is built, without the client. Here is the structure of my ...

Is it possible to automatically extract HTML code from a webpage using a function, without having to do it manually?

Is there a way to fetch the HTML code of a website after running a particular function? Here's the scenario I'm dealing with: I need to extract the link of a source embedded in an iFrame element that only becomes visible when I execute a specif ...

Tips for launching Nx serve in debug mode for Angular using VSCode

When running my Angular Nx project in the VSCode debugger, I encounter an issue with using yarn. yarn start successfully executes the nx serve command when run from a terminal. However, the same yarn start command fails when executed through VSCode debug ...

Update the background URL of a div element using an HTML tag

My question is about a CSS div with set dimensions and background that I want to change on hover. I am aware that this seems like a simple task, but what I really want to do is retrieve the background sources from within the HTML tag itself. For example: ...

Troubleshooting Angular modal fade not functioning

I am facing an issue while trying to display a component called "Login", which belongs to the class "modal fade", from another component named "navbar". Despite my attempts to trigger it by calling data-bs-toggle="modal" data-bs-target="#LoginModal" from t ...

Guide on traversing to various sections within a single page with Vuetify

I attempted to use HTML anchors to achieve this: <ul> <li><a href="#dashobard">Dashboard</a></li> </ul> Here is what my target looks like: <v-card id="dashboard"> <v-card-text class="document"> Con ...

What is the best way to set up a sidenav with router-outlet and a distinct login page with router-outlet?

My goal is to create an application with a login page that, once the user logs in, displays a navbar, toolbar, and sidenav with a router-outlet. In my app.component.html, I have set it up like this: <div *ngIf="isAuthenticated"> <app- ...

Looking to alter the CSS of an ID element when hovering over a link on your website?

Irrespective of the positioning of the links in the html, a simple hover effect can trigger changes like switching images or altering backgrounds anywhere on the website. The ideal solution would involve a straightforward method without the need for Javas ...

Enhance your AJAX calls with jQuery by confidently specifying the data type of successful responses using TypeScript

In our development process, we implement TypeScript for type hinting in our JavaScript code. Type hinting is utilized for Ajax calls as well to define the response data format within the success callback. This exemplifies how it could be structured: inter ...

It is not possible to simultaneously utilize the properties `display: inline-block` and `width: 100%`

As someone with limited CSS knowledge, I have encountered a challenge. My goal is to ensure that my website's body has a width of 100%, while also preventing the content from wrapping when the browser window is resized. To achieve this, I attempted a ...

Code for Rotating the Wheel - MINUS javascript

Exploring the possibility of creating a spin the wheel effect like this using only HTML and CSS, no Javascript involved Seeking references or examples to determine feasibility. ...

Manage your video playback by tracking the movement of your mouse on the screen

Is it possible to use mouse position on screen to control a video? Imagine, if I have my cursor on the left side of the screen, the video starts from the first frame. But as I move my cursor to the right side, the video progresses until the cursor reaches ...

What is the correct way to handle the return value of an useAsyncData function in Nuxt 3?

How can I display the retrieved 'data' from a useAsyncData function that fetches information from a pinia store? <script setup lang="ts"> import { useSale } from "~/stores/sale"; const saleStore = useSale(); const { da ...

Having trouble with my PHP index not properly redirecting to the dashboard file after logging in

I have created a login form and implemented some functionalities. One of the key features is redirecting to the dashboard file after successful password validation. I attempted to troubleshoot using chatgpt, but the issue persists. I am reaching out for as ...

The appearance and functionality of the app undergo a noticeable transformation after being bundled with Webpack

After successfully migrating my Angular 2 project from SystemJS to Webpack using the latest version of Angular2-CLI, I noticed some unexpected changes in the design of the page. Despite minimal adjustments to the project files and Angular2 code during the ...