Jerry's Blog

Recording what I learned everyday

View on GitHub


25 June 2019

Angular (12) -- Routing

by Jerry Zhang

Day 20: Angular Routing

Nested Routes

We can add some children for one path like this:

{ path: 'servers', component: ServersComponent, children: [
      { path: ':id', component: ServerComponent },
      { path: ':id/edit', component: EditServerComponent }
    ] },

Then we can add a <router-outlet></router-outlet> at wherever we want to replace the content.

<div class="col-xs-12 col-sm-4">
    <router-outlet></router-outlet>
</div>

Preserving Parameters

Adding queryParamsHandling to the navigate method, and set it to preserve. We can save the parameters in the URL.

onEdit() {
    this.router.navigate(['edit'], {relativeTo: this.route, queryParamsHandling: 'preserve'});
  }

Redirect, Setting up a route which handles all error routes

ng g c page-not-found
{ path: 'not-found', component: PageNotFoundComponent },
{ path: '**', redirectTo: '/not-found' }

Make sure that the star star component is the last one. In this way, any route that is not defined will be redirected to the not-found path.

Do not use redirection for empty route

The default matching strategy is “prefix” , Angular checks if the path you entered in the URL does start with the path specified in the route. For example,

{ path: '', redirectTo: '/somewhere-else' }

This route will now ALWAYS redirect you! Since every route starts with ''.

Another choice is changing the pathMatch.

{ path: '', redirectTo: '/somewhere-else', pathMatch: 'full' }

Outsourcing the Route Configuration

Typically, we do not put the routes in the app.module file. Instead, we should put them in another file.

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'users', component: UsersComponent, children: [
      { path: ':id/:name', component: UserComponent }
    ] },
  { path: 'servers', component: ServersComponent, children: [
      { path: ':id', component: ServerComponent },
      { path: ':id/edit', component: EditServerComponent }
    ] },
  { path: 'not-found', component: PageNotFoundComponent },
  { path: '**', redirectTo: '/not-found' }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {

}
imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
tags: Angular