How can I change the CSS class of my navbar component in Angular 2 from a different component?

Here is a custom progress bar component I created:

@Component ({
  selector: 'progress-bar',
  templateUrl: './progress-bar.component.html',
  styleUrls: ['./progress-bar.component.css']
})

export class ProgressBarComponent {

}

This is the HTML file for the progress bar:

<div class="step-by-step">
  <ul class="unstyled clearfix">
    <li class="step step-ok"><span>Step One</span></li>
    <li class="step step-ok"><span>Step Two</span></li>
    <li class="last-step step-ok"><span>Step Three</span></li>
  </ul>
</div>

Below is an example of how the app component looks like:

import {Component} from "@angular/core";

@Component ({
  selector: '',

  templateUrl: `<navbar-component></navbar-component>

<progress-bar></progress-bar>

<router-outlet></router-outlet>`
})

export class AppConfigurationComponent {

}

I have created separate components for each page in my app (three in total). The goal is to be able to dynamically set the CSS class of the progress bar as I navigate through the pages.

Image of the progress bar can be found here.

Answer №1

There are various ways to achieve this task, consider implementing the following code within the ProgressBarComponent

export class ProgressBarComponent implements OnInit {

  step = {
    one: true,
    two: false,
    three: false
  }

  constructor(private router: Router) {
  }

  ngOnInit() {

    this.router.events.subscribe(event => {

      if (event instanceof NavigationEnd) {

          this.setStep(event.path);
      });
  }
  
  setStep(path){
  
    //replace the string with your actual component path
    this.step.two = (path === '/secondPage' || path === '/thirdPage') ? true : false;
    this.step.three = (path === '/thirdPage') ? true : false;
  }
}
<div class="step-by-step">
  <ul class="unstyled clearfix">
    <li class="step" [class.step-ok]="step.one"><span>step one</span></li>
    <li class="step" [class.step-ok]="step.two"><span>step two</span></li>
    <li class="last-step" [class.step-ok]="step.three"><span>step three</span></li>
  </ul>
</div>

This method should work effectively. While there are alternative solutions available, I suggest utilizing an app state management tool like ngrx/store. By updating this state from any part of your application, especially from the root component using the same approach this.router.events.subscribe, your Progressbar will automatically adjust according to the changes in the state

Answer №2

Give this a shot within the appropriate component

constructor(private router: Router){ 
    if(this.router.url == "/componentName") {
        $("progress-bar").addClass("home"); // Use jQuery or implement it in an Angular-friendly manner.
    }
}

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

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

Accessing property values from a map in Angular

Is there a way to retrieve a property from a map and display it in a table using Angular? I keep getting [object Object] when I try to display it. Even using property.first doesn't show anything. //model export interface UserModel { room: Map ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

TS6059 found in excluded folder

I'm facing an issue with my tsconfig.json file that looks like this: {"compilerOptions": { "module": "commonjs", ...

Encountering a JSON error in Ionic 3 due to a circular structure conversion

Hello everyone, I am a beginner in Angular 2+ and Ionic 3. I am currently attempting to submit a login form from my Ionic 3 app to my ASP.NET Web API application for token-based authentication. However, I keep encountering the following error: converting c ...

Switch statements in TypeScript may not function properly with type guards when assigning an object to a variable

I'm puzzled as to why the type guard is not working in the example provided below... Considering the following interfaces: interface ParamA { name: 'A'; aaa: boolean; } interface ParamB { name: 'B'; bbb: number; ...

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

update icon when a router link becomes active

<div class="menuItem mb-3" *ngFor="let menuItem of menuItems"> <a routerLink="{{menuItem.link}}" routerLinkActive="active"> <img src="{{menuItem.icon}}" alt="{{menuItem.name}}" /> <p class="text-center f-12">{{me ...

Text box input that displays the latter portion before the initial part

Looking for assistance with showing the end of the entered text rather than the beginning in an input field. For example, the input could be "Starting portion, Ending Portion". If the input field is limited to 14 characters, instead of displaying the firs ...

Unable to create a line break within an ion-item

I'm facing a bit of a dilemma with this straightforward issue. Can't seem to find a solution. The following code is not producing the desired outcome: <div text-wrap ion-item no-lines> "No result found. <br/> Please ent ...

The Vue CLI project, using Typescript, is facing challenges with building and running Mocha tests

My Vue 2 project, created using Vue CLi, is encountering numerous errors. While it compiles fine for development purposes, running unit tests or building for production results in a cascade of issues. Displayed below are some sample errors, along with sni ...

Creating Angular 2 projects effortlessly with Angular-Cli 1.0.0: A step-by-step guide

With the official release of Angular-Cli v.1.0.0 and Angular v.4.0.0, the default project created with ng new is now an Angular v.4 project. However, I still prefer to create Angular v.2 projects by default. Is there a way to set this as a global config s ...

Experiencing the 'invalid_form_data' error while attempting to upload a file to the Slack API via the files.upload method in Angular 8

I am currently working on a project that involves collecting form data, including a file upload. I am trying to implement a feature where the uploaded file is automatically sent to a Slack channel upon submission of the form. Despite following the guidance ...

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

The error message states: "There is no property named 'controls' on the type 'AbstractControl<any, any>'"

I have encountered an issue with my reactive form on Angular versions above 13. Despite using FormGroup and FormArray with proper typecasting, I am still facing errors. How can I resolve this? Working code in Angular 11: here Error shown in Angular 15: h ...

Experiencing a hitch when attempting to deploy an Angular 2 application on Heroku

Encountering the sh: 1: tsc: not found Error when attempting to deploy an Angular 2 app on Heroku. Using Node version: v7.2.0 and npm Version: v4.0.3. View the error on Heroku Any suggestions on how to resolve this issue? ...

Animations in Angular fail to operate within mat-tabs after switching back when custom components are being utilized

I am facing a similar issue as Olafvv with my angular 16 project. The problem occurs in a mat-tab-group where the :enter animations do not work when navigating away from a tab and then returning to it. However, in my case, the issue lies within a custom su ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...

Creating React components dynamically using the number of objects passed as props

When attempting to create components based on the number specified in an object's files property, I keep encountering an error indicating that the parent component has too many children. If the files property is set to 5, does anyone have a solution ...

Tips for integrating external libraries (npm packages) in Ionic 4 applications

With the changes in Ionic 4, I am seeking a definitive guide on implementing third party libraries, such as "rss-parser". I have reviewed this article which seems to be the latest resource on the topic: https://ionicframework.com/docs/v3/developer-resour ...