Setting style based on the condition of the router URL

I am currently facing an issue with a global script in Angular 10 that is supposed to evaluate the current path and apply a style to the navigation bar conditionally. However, it seems to fail at times when using router links. I am wondering if there is a more efficient way to achieve this in Angular/Typescript that works seamlessly with router links.

$(document).ready(function(){
  if (window.location.pathname != "/") {
    $('#main-nav').css('background-color', 'black');
  }
});

The functionality I want is simple: change the navbar color to black if the page is not the homepage.

I have come across suggestions about using ngOnInitView but I am unsure about where to implement it (should it be within my navbar component?).

Any insights or guidance on this issue would be greatly appreciated.

Answer №1

To monitor changes in the router using your navbar component, you can make use of the Angular Router service (@angular/router).

isPage: boolean = false;

constructor(private router: Router) {}

ngOnInit(): void {
  this.router.events
    .pipe(filter(event => event instanceof NavigationEnd))  
    .subscribe((event: NavigationEnd) => {
        this.isPage = event.url === "/"; // Set a boolean based on current URL
    });
}

You have multiple options for updating the style of your navbar in the HTML. One approach is to utilize ngClass or ngStyle. For example;

<div id="main-nav" [style.background-color]="isPage ? 'black' : null">
    Main
</div>

Answer №2

To retrieve the route, you can implement the following approach:

Utilize Router from @angular/router

Within the constructor:

constructor(private router: Router){}

You can then access the URL route using:

this.router.url

If you need to monitor for changes, subscribe to it by:

this.router.events.subscribe((value) => {
  If (val instance of NavigationEnd){
    this.onRoute = val.url;
  }
}

Keep in mind that this.onRoute is a declared variable public onRoute: string

You can then utilize the onRoute variable to assess information about the route.

In addition, within the HTML, you can incorporate the noHomeBackground class (which represents your custom styling) when the condition this.onRoute!=='/' is met.

<div [class.noHomeBackgroud]="this.onRoute!=='/'">
...
</div>

Answer №3

If you want to dynamically change the style of an HTML element in Angular based on the route it is navigating, you can follow these steps:

Firstly, in the div.component.html file

<div [ngClass]="[router.isActive('/colored-div', true) ? 'colored-div': 'non-colored-div' ]">

By using [ngClass] within the HTML element, you are conditionally applying CSS classes depending on whether the route is active or not.

The isActive() function checks if the specified URL is currently active or not.

Next, in the div.component.css file

div {
   width:90%;
   height:10vh;
}
.colored-div {
   background-color: skyblue;
}

.non-colored-div {
   background-color: transparent;
}

Lastly, inside the constructor of the div.component.ts file

constructor(public router: Router){}

It's important to note that the router variable needs to be marked as public in order for it to be accessible within the template.

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

In Angular 9, when using ngOnChange, the attribute SimpleChanges.firstChange will always be false even if the value has been

There is a specific task I am trying to accomplish with my component. I need to execute a certain action only the first time the @Input property changes. However, I have encountered an issue where the value of changes.firstChange always returns as false, r ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

I am struggling to set a required input in Angular2

I am new to Angular and currently working on a project that requires input validation to ensure that no field is left blank. The project consists of an HTML file along with a .ts file for functionality. Below is a snippet from the HTML: <div class="f ...

Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error: Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceServic ...

ng2-dragula error: issues with setting options and dropping version

It seems that version 1.5.0 supports this.dragulaService.setOptions, while version 2.1.1 does not, and vice versa with this.dragulaService.drop subscribe where version 2.1.1 supports it but 1.5.0 does not. Check out the Stackblitz Fork for version 1.5.0 ...

Library of Functions in Angular 2

As I develop my application, I'm considering creating a functions library that can be utilized by various components. What would be the most effective approach to achieve this? Should I create a service containing all the functions, or rely on classes ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

Implementing Angular's Advanced Filtering Across Multiple Data Fields

I am looking to create a custom filter for a list. Here is an example of the Array of Objects: myList: [ { "id": 1, "title":"title", "city":"city name", "types":[ { ...

TypeScript purity - "The variable exports is not defined"

I encountered an issue with my simple client-server TypeScript application where every import statement in my client.ts file triggers a ReferenceError: exports is not defined error in the browser after loading the HTML. Here is the project structure: root ...

Having trouble executing a method from a template in Angular 5?

Angular has a useful capability that almost every developer has utilized at some point: calling methods from templates. I've personally been using this feature for months without any issues. However, recently I encountered a problem. I have a menu co ...

Error encountered in spyOn TS when passing array iteration instead of a string

Instead of repeating test cases with minor adjustments, I have implemented an Array and iterated through it. However, I am encountering a TS error in test when passed from the Array instead of as a string testLink Error: No overload matches this call. ...

Develop a directive for transforming data

In my latest project, I am looking to develop a LoaderDirective that can fetch an observable, display a spinner while loading the data, and then switch to showing the actual data once loaded. I also want it to expose the loaded data using the 'as&apos ...

Executing asynchronous functions in Angular 2

In my Angular demo.ts file, I have included two functions fetchTables() and fetchAllTables() inside the constructor of a class. Both functions make API calls. However, I am facing an issue where one of the calls fails consistently. Sometimes fetchTables() ...

Adding extra fields to an existing JSON response in a TypeScript REST API

I am in need of an additional column to be added to my response data. Currently, I am fetching data from multiple REST endpoints one by one and merging the results into a single JSON format to display them in an Angular Mat table. The columns that I want t ...

Utilizing a directive in contexts beyond a component

I have developed a popover module that consists of two components and three directives. However, I am encountering an issue where I am unable to utilize the directives outside of the main component. Whenever I try to do so, I face an editor error stating: ...

Azure Function responding with a 401 error code upon passing parameters through a proxy

I have a situation where I am working with an Angular service that includes a GET request with parameters currentPage and postsPerPage. In my efforts to pass these parameters to an Azure function, I came across a tutorial advising me to set up proxies. Wh ...

Enhancing the loading speed of hefty Angular components

The issue I encountered involved a large component that loads over 1000 data elements, populated by a service called only once. Initially, the service was being called each time the component initialized, which seemed to be causing performance problems. To ...

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

AngularMap with mapping as the value

Can I implement a Map<string, Map<string, number>> collection in my Angular project? I attempted to create and initialize the variable, but encountered an error when trying to set values. Here is an example: //define variable public players: M ...