Search code examples
angular-routing

Angular routerLink routes properly but route.navigate in component routes to default path


The Basic Sample is created
The Source Code is Uploaded Here and Deployed Here

  • A route is set with path :"products"
  • In app.template.html using routerLink directive a route is set -> when "Products" gets clicked --> The route "products" is opened as expected, but activating the same route through code (this.route.navigate(['/products']) in "app.component.ts" navigates to this 'home'.

This is basic but weird, where have I gone wrong ?


Solution

  • It's getting redirected on your app.component.html on line 19:

    <a class="nav-link" href="#" (click)="navigateBack()"> Products(navigated in Component)</a>
    

    This tag has href="#" so the page is getting routed to your root because your app-routing.module.ts file is redirecting to home.

      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: '**', redirectTo: 'home', pathMatch: 'full' }
    

    So, remove href="#" with [routerLink]="[]" and it should resolve the issue.