21

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?

0

5 Answers 5

38

If you want something basic that works:

if (this.router.url.indexOf('/test/sort') > -1) {
  this.active = 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am tempted to downvote this answer on the basis that you have said it isn't a good answer and there are far better solutions...
27

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.

Comments

4

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

    }

}

Comments

0

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.

Comments

0

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

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.