Can the routing module be utilized to invoke functions that retrieve the current routing value?

When working with Angular, I have the need to call certain functions that will return a value based on the current page routing. These functions are currently located within the element that needs to be changed by the route's component.

I know how to code these functions, but I have a couple of questions: 1. Do I need to create a service like "ColorService" to handle these functions? 2. Should I call these functions from the components of the elements I want to change based on routing, or from the routing module itself?

Here is an example of my current routing module:

import { NgModule } from '@angular/core';
import { HomeHebComponent } from '../components/home-heb/home-heb.component';
... (more components imported)
export class RoutingModule { }

Below is an example of a function for changing colors in the menu file:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
})
export class MenuComponent implements OnInit {
    private route: string;
  constructor(private router: Router) {
      router.events.subscribe( val => {
              this.route = window.location.pathname;
              console.log(this.route);
      });
   }

  ngOnInit() {}

  // Toggle color based on routing
  private toggleColorAboutRouting(): string {
     return this.route === '/heb/about' ? 'white' : 'initial';
  }
}

Answer №1

To implement functionality in your component, you can utilize the Angular Router and analyze the url property.

export class MenuComponent implements OnInit {
  private currentRoute: string;

  constructor(router: Router) {}

  ngOnInit() {
      this.currentRoute = this.handleRoutingColor(this.router.url);
  }

// Changes color based on routing
  private handleRoutingColor(url: string): string {
      return this.currentRoute === '/heb/about' ?  'white' :  'initial';
  }
}

Answer №2

you have the ability to pass a data object to the route

{ path: 'heb/about', component: AboutHebComponent, data: {color: 'white'}},

which will result in:

import { NgModule } from '@angular/core';
import { HomeHebComponent } from '../components/home-heb/home-heb.component';
import { AboutHebComponent } from '../components/about-heb/about-heb.component';
import { ContactHebComponent } from '../components/contact-heb/contact-heb.component';
import { GalleryComponent } from '../components/gallery/gallery.component';
import { Routes, RouterModule } from '@angular/router';
import { Page404Component } from '../components/page404/page404.component';
import { PlywoodHebComponent } from '../components/plywood-heb/plywood-heb.component';
import { MdfHebComponent } from '../components/mdf-heb/mdf-heb.component';
import { TegoTlatOsbHebComponent } from '../components/tego-tlat-osb-heb/tego-tlat-osb-heb.component';
import { HardwoodHebComponent } from '../components/hardwood-heb/hardwood-heb.component';
import { MapHebComponent } from '../components/map-heb/map-heb.component';

const routes: Routes = [
    { path: 'heb/home', component: HomeHebComponent},
    { path: 'heb/about', component: AboutHebComponent, data: {color: 'white'}},
    { path: 'heb/plywood1', component: PlywoodHebComponent},
    { path: 'heb/mdf', component: MdfHebComponent},
    { path: 'heb/hardwood', component: HardwoodHebComponent},
    { path: 'heb/plywood2', component: TegoTlatOsbHebComponent},
    { path: 'heb/contact', component: ContactHebComponent},
    { path: 'heb/map', component: MapHebComponent},
    { path: 'heb/gallery', component: GalleryComponent},
    { path: '', redirectTo: '/heb/home', pathMatch: 'full' },
    { path: '**', component: Page404Component }

];


@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ]
})
export class RoutingModule { }

you can retrieve this data in your component using ActivatedRoute

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
color = 'initial';
export class MenuComponent implements OnInit {
    private route: string;
  constructor(location: Location, private router: Router, private route: ActivatedRoute,) {
     route.data.subscribe(
       (data)=> this.color = data.color);

}

in this example, I simply assigned the value of the variable color Edited.

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

Typescript - filtering out null values from JSON object

I am facing an issue with my service method that saves a date on the server. When this method sends the date to the server, it includes fields with null values in the JSON. How can I exclude these fields with null values? public create<T>(post: any) ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

Error in file @angular/service-worker/src/module.d.ts at line 30, character 9: The type 'ModuleWithProviders' is not a generic type

https://i.sstatic.net/01bwW.pngI have successfully integrated "angular-push-notifications" into my angular-4 project by following the instructions from the link below: I have configured the "Service Workers" as shown below 1. Install the package using np ...

What is the solution for the error "does not exist on type 'HTMLTableDataCellElement'" in Angular?

When working on my Angular project, I implemented a PrimeNG p-table component. <p-table [value]="users" class="user-roles-table" [rows]="5" [showCurrentPageReport]="true" [ ...

Is there a way to import a module generated by typescript using its name directly in JavaScript?

I am trying to bring a function from a typescript-generated module into the global namespace of JavaScript. The typescript module I have is called foo.ts: export const fooFn = (): string => { return "hello"; }; Below is the structure of my HTML file ...

I want to learn how to pull all the files from a Google Drive folder using the Google Drive API and then transfer them to a Spring Boot server,

I need to download all the files in a folder using the Google Drive API. Unfortunately, this API does not support downloading all files at once. The workaround is to retrieve all the files in the folder and then download each file individually. I have succ ...

Toggle the selection of all checkboxes in TypeScript

Help needed with creating a single select/deselect all checkbox in Typescript. The current code successfully selects all when checked but fails to deselect all when unchecked. selectAllLocations() { var selectAll = < HTMLInputElement > document. ...

Having trouble with vscode compiling the typescript file?

Even though I diligently followed the tutorial provided by vscode on compiling typescript code, I encountered a problem. The configurations were set up as per the instructions in the tutorial, but when I tried to run the code without debugging, I received ...

Should Angular 6 developers consider storing JSON web tokens in LocalStorage or Session Storage?

After doing a lot of research, I have come across various discussions regarding the storing of JSON web tokens in different areas like local storage, session storage, and cookies. Each method has its own advantages and disadvantages that developers conside ...

Troubleshooting the accessibility issue between Docker node container and Angular/Node.js

After deciding to follow the angular tutorial provided on the angular website, I made the choice to download the "node" image from dockerhub. To ensure proper functionality, I carefully mapped container ports 4200 and 8080 to my physical Windows machine po ...

Adding onBlur validation for radio buttons and checkboxes in Angular Material UI

Currently, I am working on implementing checkboxes and radio buttons using Angular Material UI. My main issue lies in achieving the desired red outline effect when a required field is left unselected by the user. Even after applying the necessary 'req ...

Is there a marble experiment that will alter its results when a function is executed?

Within Angular 8, there exists a service that contains a readonly Observable property. This property is created from a BehaviorSubject<string> which holds a string describing the current state of the service. Additionally, the service includes method ...

Issue with data not being assigned to TypeScript class variable

Utilizing an http call to fetch data from the backend, I am able to see the retrieved data in the browser console. However, for some reason, the data is not being assigned to the class variable as expected. The code snippet is shown below: "use strict"; ...

Key-based iterative function for intercepting values

Looking to extract values associated with the key text from a large JSON file. Here is an example snippet: type":"doc", "content":[ { "type":"paragraph", "content":[ ...

Tips for updating the display after making an angular $http request using rxjs Observables

I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows: userInfo() : Rx.Observable<IUserInfo> { ...

I encountered an error message while using the application. Any suggestions on how to resolve this issue?

Error: Route configuration for '' is invalid. Component, redirectTo, children, or loadChildren must be provided. Within app.module.ts, RouterModule.forRoot([ { path:'', loadChildren:'./mainhomemodule/mainhomemodule.modu ...

What sets Angular 2 Components apart from traditional Web Components?

There seems to be some confusion here. Is it possible for an Angular 2 Component to be utilized outside of its Angular scope similar to a Web Component? Or is there more to it than meets the eye? ...

Use a mock HTTP response instead of making an actual server call in Angular 4

I am facing a scenario where I have a function myFunc() that I subscribe to. When this function is called with X parameter, I expect a regular HTTP response from the server. However, if it is called without the X parameter, I want it to return a 'mo ...

Structuring your Angular 6 application and server project

What is the recommended project structure when developing an Angular 6 application and an API server that need to share type definitions? For example: On the client side: this.httpService.get<Hero[]>(apiUrl + '/heroes') On the server si ...