None
None

Reputation: 9247

Check if router.url contains specific string?

I have this :

   if (this.router.url === '/test/sort') {

                    this.active = 0;
                }

Problem is that sometimes url will be test/sort?procesId=11 and than it will not enter in if statement. Any suggestion how can i do that?

Upvotes: 21

Views: 59692

Answers (5)

Unax Gómez
Unax Gómez

Reputation: 17

If using this.router.url returns a slash, you can use this.location.path() just like this:

import { Location } from '@angular/common';

constructor(
    private location: Location
  ) {}

if (this.location.path().indexOf('/test/sort') > -1) {
      this.active = 0;
    }

Upvotes: 0

testing
testing

Reputation: 20289

This would be another possibility:

if (this.activatedRouter.snapshot.url.some(url => url.path.includes('test')) &&
    this.activatedRouter.snapshot.url.some(url => url.path.includes('sort'))) {
    this.active = 0;
}

Modify it for your needs.

Upvotes: 0

Marko Letic
Marko Letic

Reputation: 2550

You can also use:

if (this.router.url.includes('/test/sort')) 
{  
     this.active = 0; 
}

Method String.includes(searchString: string, position?: number): boolean - Returns true if searchString appears as a substring of the result of converting this object to a String, at one or more positions that are greater than or equal to position; otherwise, returns false.

Upvotes: 27

Carsten
Carsten

Reputation: 4208

If you want something basic that works:

if (this.router.url.indexOf('/test/sort') > -1) {
  this.active = 0;
}

Upvotes: 38

Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

You can use LocationStrategy to get url without parameters.

import {LocationStrategy} from '@angular/common';


export class AppComponent implements OnInit {

    constructor(private url:LocationStrategy) { }

    ngOnInit() {

        console.log(this.url.path());
        if(this.url.path()==='/test/sort'){

         this.active=0; 
         }

    }

}

Upvotes: 4

Related Questions