Angular 5 – Alternative for parameterized routing

Issue

My use case is this:

  • In the main page, I have 2 buttons, and either of them will lead me to the same screen. When I say ‘same screen’, I mean exactly the same component
  • At the target component, I need to know which button leads me here. So that data will be handled differently.

What I have done so far to make it work is to use parameterized routes (btn):

export const routes: Routes = [
   //blah
  { path: 'configuration/:btn', component: ConfigurationComponent, data : { title: 'Configuration' } },
   //blah
];

export class ConfigurationComponent implements OnInit {
    ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.btnType = +params['btn'];
    });

    //this.btnType will be used to identify which button was clicked
}

First Button

<a [routerLink]="['/configuration', '1']">

Second Button

<a [routerLink]="['/configuration', '2']">

Problem that I want to solve:

The url is shown as:

configuration/1 and configuration/2

But I want to show it as:

configuration/HELLO and configuration/BYEBYE

Can this be done via parameterized routing? If not, any alternatives?

Solution

Your current solution is able to handle this no problem.
The only thing you need to do is update these:

this.btnType = +params['btn'];
<a [routerLink]="['/configuration', '1']">
<a [routerLink]="['/configuration', '2']">

to be:

this.btnType = params['btn'];
<a [routerLink]="['/configuration', 'HELLO']">
<a [routerLink]="['/configuration', 'BYEBYE']">

Without the +, the param will remain a string value and will be either ‘HELLO’ or ‘BYEBYE’ depending on your route.

Answered By – Simon K

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.