How to update this.router.url property based on some condition in Angular

2.3k Views Asked by At

I am working on angular application where I want to update router url on some condition. below is the sample code:-

console.log(this.router.url) // it prints '/users'
this.location.replaceState('/users/1') // it updates the url bar with new url
console.log(this.router.url)  //it prints same again '/user'

is there any way i can change the current route url without refreshing or reloading the page.

2

There are 2 best solutions below

0
Walter Luszczyk On

you probably should navigate to new route

if (condition) {
  this.router.navigate('/users/1');
}

In Angular (as SPA) it won't refresh or reload page but instantiate component for new route. If you want display user information in only one div in the page without refreshing the rest (i.e. list of users), you can make use of router-outlet.

You can learn more here

0
Farouk Mhamdi On

you should add a condition in the ngOnInit if (this.router.url === '/cms/page/edit') { this.page1= true

and then add a *ngIf="page1" or *ngIf="!page1" to the html balise.

this worked for me ;).