Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular routing doesn't refresh the page

Tags:

angular

I want to be able to change data on my page based on the URL route, i.e. test/1 gets me data set 1, test/2 gets me data set 2. However if i am already on test/1 and try to navigate to test/2 (and vice versa) using router navigate, it changes the url but that's it, nothing else gets triggered.

I have following definition for my route:

const routes: Routes = [
  {
    path: 'test',
    children: [
      {
        path: ':id',
        component: TestComponent
      },
      { path: '**', redirectTo: '', pathMatch: 'full' }
    ]
  },
];

TS Component:

value: any;

constructor(private router: Router, private, private route: ActivatedRoute) { 
   this.value = this.route.snapshot.params.id;
}

goToPage(value: any) {
    this.router.navigate(['/test', value]);
}

my html component:

{{value}}

<button (click)="goToPage(1)">One</button>
<button (click)="goToPage(2)">Two</button>

I've also tried adding { onSameUrlNavigation: 'reload' } to RouterModule.forRoot, still doesn't do anything.

NOTE: Problem is not to get the parameter, the problem is the refresh of the page that has to take place to trigger all processes associated with the new parameter.

like image 290
Aeseir Avatar asked Mar 05 '26 16:03

Aeseir


1 Answers

Option 1: Listen to route changes and initialize page

constructor(private router: Router, private, private route: ActivatedRoute) {
   this.value = this.route.snapshot.params.id; // for first entry
   route.params.subscribe(val => {
     this.value = this.route.snapshot.params.id;
     // put the code to initialize the page
   });

}

Option 2: Reinitialize the page on route navigation

goToPage(value: any) {
    this.router.routeReuseStrategy.shouldReuseRoute = function () {
        return false;
    }
    this.router.onSameUrlNavigation = 'reload';
    this.router.navigate(['/test', value]);
}
like image 130
Jp Vinjamoori Avatar answered Mar 07 '26 08:03

Jp Vinjamoori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!