3

Am new to angular2 and am looking forward to add parameters to a router when the current url doesnt have the said param on click event

This is what i have tried

The button

<button (click)="onStats()">Proceed to stats </button>

Now the function

onStats(){
    let url = this.router.url;

    //here i would like to check if the router constains ?stats
    //am stuck

}

So basically i have my urls as

locahost:4200/users/roles
localhost:4200/managers
...............

now i would like to add ?stats at the end of url if it doesnt exists hence the new url to be

locahost:4200/users/roles?stats
locahost:4200/managers?stats
...........

In my routing i have setup

{path:'user/roles:stats' , component:UserRolesStats}

How do i go about it

I would not like to hardcode the routerlink="users/roles?stats" since other areas also use this stats functionalities as well

2 Answers 2

5

Inspect current query params

Use the ActivatedRoute service to subscribe to the query parameters of the current route. You can inspect if ?stats exists like this:

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}
private stats: boolean;    

ngOnInit() {
    this.route
      .queryParams
      .map(params => params['stats'])
      .subscribe(stats => this.stats = !!stats);
  }

A lot of good information to read in the official docs:

Query Parameters and Fragments are also available through the ActivatedRoute service. Just like route parameters, the query parameters and fragments are provided as an Observable

Adding query params during navigation

To prepend a query parameter when you navigate, you can add the NavigationExtras parameter to the .navigate() method of the router or add the [queryParams] directive to your link.

From code:

this.router.navigate(['/users/roles'], { queryParams: { stats: true } });

From template:

<a [routerLink]="['/users/roles']" [queryParams]="{ stats: true }">
Sign up to request clarification or add additional context in comments.

1 Comment

@GEOFFREYMWANGI added some more to the answer. Is this what you are looking for?
0

I use "import { Router } from "@angular/router";" and this allows me to do the following function and more.

  this.route.queryParams.subscribe((params)=> {
  //check lead Id here
  if(params['id']){
    console.log(params['id']);
  } else {
    console.log('id not found in params')
  }
});

Here is a link to example of how to navigate and add parameters to your url and much more. Angular2-routing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.