Search code examples
angulartypescriptangular-router

Angular 6 same router.navigate causes refresh when called from another component


I have a routing module as follows:

App-routing module

const routes: Routes = [
  {
    path: '',
    redirectTo: environment.devRedirect,
    pathMatch: 'full',
    canActivate: [AuthenticationGuard]
  },
  {
    path: 'customers/:customerId/contracts/:contractId',
    loadChildren: './grouping/grouping-routing.module#GroupingRoutingModule'
    canActivate: [AuthenticationGuard],
  }
];

And a child component with routes:

const routes: Routes = [
      {
        path: 'create',
        component: CreateEditComponent,
        data: { animation: 'create' },
        canActivate: [ AuthenticationGuard ]
      },
      {
        path: ':groupId/edit',
        component: CreateEditComponent,
        data: { animation: 'edit' },
        canActivate: [ AuthenticationGuard ]
      },
      {
        path: '',
        component: OverviewComponent,
        data: { animation: 'overview' },
        canActivate: [ AuthenticationGuard ]
      }
];

I have a top level navbar component which sits in the app.component.html.

Both the navbar component and the CreateEditComponent have a function that looks like below. Both are called using a button with (click):

  goToOverview(): void {
    this._router.navigate(['customers/:customerId/contracts/:contractId']);
  }

When I debug the router object both look exactly the same i.e. have all the same paths etc.

My problem is that the navbar function routes correctly but the CreateEditComponent navigates, appends a ? then reloads the page. What am I missing here and why do two seemingly similar calls have such different results when the activatedRoute objects are identical?


Solution

  • Finally figured out what was causing the refresh. The button with the (click) handler that was causing the refresh was sitting inside a <form> tag. Whenever the click function was called which did the router.navigate it caused a form submission which seems to be the cause