Home > Software engineering >  how can pass different parameters using [routerLink] or router.navigate to a component?
how can pass different parameters using [routerLink] or router.navigate to a component?

Time:02-13

I configured app-routing.module.ts as following:

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

and also in app.component.html have:

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

and in the barnches.component.ts I coded as bellow:

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}`);
  }

till here everything comes correct, and URL is changed once the respective link is clicked, such as :

http://localhost:4200/branches/engineering

http://localhost:4200/branches/baseSciense

http://localhost:4200/branches/humanities

but the property branch in Branches component is not changed and has same value (engineering) for different parameters in log of the console. it is illogical for me!

how can solve this problem as pass different parameters to and capture them into branches component? Best regards

CodePudding user response:

You need to move your console.log within the subscription. Most of the code related to this feature will need to take place within the subscription. The Component doesn't re-render on url change because it is loading the same component and angular doesn't re-render components if it is the same component.

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() {
    // Set the value every time the URL param changes.
    this.route.params.subscribe(({ branch }) => {
      this.branch = branch;
      console.log('branch:', this.branch);
    });
  }
}

CodePudding user response:

In your component you can subscribe to router events and listen for them like this.

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