doovers
doovers

Reputation: 8675

Child route redirect not working

I'm trying to set up the default child route for an angular component but I can't seem to get it working with either of the methods below. Any ideas where I'm going wrong?

RouterModule.forRoot([
  { path: 'signin', component: SignInComponent, canActivate: [UnauthGuard] },
  { path: '', component: MainComponent, canActivate: [AuthGuard] },
]);

RouterModule.forChild([{
  path: '',
  component: MainComponent,
  children: [
    { path: 'dashboard', component: DashboardComponent },
    { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
    // { path: '', component: DashboardComponent },
  ]
}]);

Upvotes: 0

Views: 1189

Answers (2)

Z. Bagley
Z. Bagley

Reputation: 9260

The problem is that your base href route doesn't load the forChild route anywhere. There are several different methods for loading children into routes, but here's my standard:

In your base app routing.module.ts, import the sub-module that is holding your child routes.

import { ChildModule } from './child/child.module';

For production builds I add a simple export function for AOT compiling:

export function loadChildModule() {
  return ChildModule;
}

and your @NgModule should declare the child routes like:

{ path: 'dashboard', loadChildren: loadChildModoule },
{ path: '', component: MainComponent }

Your child/child.module.ts will need to import the routes from child/child-routing.modules.ts.

child.module will contain:

import { ChildRoutingModule } from './child-routing.module';
...
*NgModule({
  imports: [
    CommonModule,
    ChildRoutingModule
  ]
...

and your child-routing.module:

import { DashboardComponent } from './dashboard/dashboard.component';
import { ChildComponent2 } from './child2/child2.component';
import { ChildComponent3 } from './child3/child3.component';

const routes: Routes = [
  { path: 'child2', component: ChildComponent2 },
  { path: 'child3', component: ChildComponent3 },
  { path: 'dashboard', component: DashboardComponent },
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ChildRoutingModule { }

You can add children to the child module as well in the same way you added them to the the main app RoutingModule. Also note, that you can use a similar setup as your .forChild routes posted in the question. The only difference is you will have to use at least one named route (for example your main component would have path: 'home' and there should be a redirect to path: '' to redirectTo: 'home' ) in each .forChild.

Upvotes: 1

Tiago Pereira
Tiago Pereira

Reputation: 29

Write: <router-outlet></router-outlet> on father component. in this case write on MainComponent.

Upvotes: 0

Related Questions