What is the best way to send various parameters to a component using [routerLink] or router.navigate?

My app-routing.module.ts is configured as shown below:

const routes: Routes = [
  {
    path: "branches/:branch",
    component: BranchesComponent
  },
  
  // ...
];

In addition, in my app.component.html, I have the following code:

<li>
      <a [routerLink]="['/branches', 'engineering']"> engineering </a>
    </li>
    <li>
      <a [routerLink]="['/branches', 'baseSciense']"> baseSciense</a>
    </li>
    <li>
      <a [routerLink]="['/branches', 'humanities']"> humanities</a>
    </li>
  </ul>
  
  <router-outlet></router-outlet>

Furthermore, in the branches.component.ts file, I implemented the following code:

branch: string ='';
  
  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
  
    this.route.params.subscribe(({branch: branch1}) => this.branch = branch1);
    
    // I also tried this code:
    // this.route.params.subscribe(branch => this.branch = branch['branch']);
    
    // unfortunately, bellow codes have error on p.branch and params.branch! why?
    // this.route.params.subscribe(p => this.branch = p.branch)
    // this.branch = this.route.snapshot.params.branch;
    
    console.log(`branch is : ${this.branch}`);
  }

Everything seems to work correctly up to this point, with the URL changing when different links are clicked. For example:

http://localhost:4200/branches/engineering

http://localhost:4200/branches/baseSciense

http://localhost:4200/branches/humanities

However, despite changing parameters in the URL, the value of the branch property in the Branches component remains the same (engineering). This inconsistency puzzles me!

How can I resolve this issue so that I can pass different parameters and capture them within the Branches component? Thank you.

Answer №1

To ensure proper functionality, make sure to place your console.log statement within the subscription block. It is important for most of the code associated with this feature to be executed within the subscription. Keep in mind that the Component will not re-render upon a URL change if it is loading the same component, as Angular does not trigger re-renders for identical components.

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

@Component({
  template: 'Branch: {{branch}}',
})
export class BranchesComponent implements OnInit {
  branch = '';

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    // Update the value whenever the URL parameter changes.
    this.route.params.subscribe(({ branch }) => {
      this.branch = branch;
      console.log('branch:', this.branch);
    });
  }
}

Answer №2

To incorporate router events in your component, you can set up a subscription and listen for them as demonstrated below.

this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe(event => {
  console.log((event as NavigationEnd).url);
});

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

The function window.open has been disabled on codepen.io site

My dilemma involves a button designed to open a random Wikipedia page. While the code works perfectly in the CodePen editor, I encounter issues when opening it in full-page view. The problem arises when the log displays 'window.open is disabled'. ...

Tips for accessing a variable value within a JavaScript function

I am currently facing an issue where I am unable to retrieve a variable from a JavaScript function and use it outside of the function. While I can successfully output the variable value inside the function, I am struggling to access it elsewhere in my sc ...

Displaying images in Ionic from a JSON URL source

I am having trouble getting an image from a JSON to display on an Ionic card. Although I can see the JSON response in the console log, the image is not showing up on the card, leaving it blank. It seems like I'm making a mistake in the HTML code. Any ...

Can you explain the concept of the "one true source"?

After reviewing this particular article, I came across a significant statement in the "Controlled Components" section: The integration of both can be achieved by ensuring that the React state is considered as the “single source of truth”. Can you ...

Generate a unique slug in Javascript using the provided name and then show it in a disabled input field

Currently, I am working on a feature to generate a slug dynamically using Javascript. I want my users to be able to preview the slug before submitting the form. Below is the Javascript code I have written: function createSlug(text) { return text .toS ...

Displaying ASP.Net Core Application on local IIS - Unable to locate content

I started a new project in Visual Studio Code by running the following command: dotnet new angular --use-local-db Afterwards, I upgraded Angular from version 8 to 10 and completed the project. To test it, I used dotnet watch run Everything was running ...

Find a specific value within a complex array of objects in Angular 2

Recently delving into Angular 2, I am seeking guidance on the best approach for a particular use-case. My array of Objects is structured as follows: users : Array<Object> = [{ id: 1, tags: [{ name: 'foo', age: 21 ...

The information is failing to display properly within the mat-menu

Recently, I've been working on creating a navbar that includes a submenu. Even though the navigation bar data is loading properly, I am facing some issues with the submenu functionality. As a beginner in this area, I would appreciate any help or guida ...

Using Angular2 - How to pass the router parameter as a variable in ngForm

Struggling to pass a router param (id) to an ngForm and then to an event emitter. I am able to retrieve the id from the router successfully, but when trying to assign it to my singleOpenHome object, I encounter an undefined error: @Input() singleOpenHome: ...

The error notification is not appearing in the correct location

I've been troubleshooting my jQuery error function for hours now (including the success function). I'm struggling to figure out how to display an error message only below the button that I click. To help clarify my issue, I've created a JSFi ...

Ionic2: expanding menu options in the sidemenu

I'm not very familiar with ionic, but I have a question on behalf of my friend who is hesitant to ask on StackOverflow because she's unsure of how to frame her question. She simply wants to learn how to implement a submenu in an ionic 2 side men ...

Incorporating an NPM module with dependencies within the Meteor framework

I'm encountering some difficulties while attempting to integrate an NPM package into my meteor project. The specific module I am trying to utilize is the steam package. In order to make this work, I have included the meteorhacks:npm package for mete ...

Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event dat ...

This marks my initial attempt at developing an Angular project using Git Bash, and the outcome is quite remarkable

I have a project named a4app that I am trying to create, but it seems to be taking around 10 minutes to finish and is showing errors. The messages displayed are quite odd, and I suspect there may be an issue with the setup. I have not yet used the app that ...

Decoding the values in an input field

Can anyone help me with identifying links, numbers, and text in WhatsApp and other app input boxes? I also want to be able to preview the page attached to a link and style these elements separately from other text. I am currently working on a project whe ...

Error in AWS Lambda: Module 'index' not found

In my setup, I have kept it simple by using typescript. All my typescript files are compiled into a /dist directory. Debugging with Webstorm is smooth as it easily finds the handler: https://i.sstatic.net/qkxfD.png The problem arises when I try to run i ...

What changes can I make to my method in order to utilize async/await?

Within my React application, I have implemented a post request to the server using axios: onSubmit = async (results) => { try { const response = await axios.post("http://localhost:8080/simulate/", results); this.setState({results: ...

What is the reason that the for loop updates all indexes in Node.js?

Currently, I am working on a space battle program that involves nested arrays. In order to simulate fleet fighting, I have written the following code: //Roll a dice function const randomNumber = (number) => { return Math.floor(Math.random() * numbe ...

The function angularCompiler.getNextProgram is not available in the context of angular 12 when using custom-webpack configurations

Recently, I upgraded my Angular 11 project to version 12. I have incorporated the @angular-builders/custom-webpack package in my devDependencies and I am using the below command for building my Angular project. ng build --configuration=production --build ...

Contrast the positions (offsets) of two elements

I am trying to determine if one element is positioned above another by comparing their offset positions. Specifically, I need to verify whether the me element is within the bounds of the screen element using their respective offset positions. HTML Code ...