Angular Routes set default component for router-ou

2019-09-02 06:26发布

I have two modules (clientModule, AdminModule)

By default the client Module is loaded.

Client module route configuration

const _routes: Routes = [
  {
    path: ':id', component: appComponent, children: [
      { path: 'page1', component: page1Component},
      { path: 'admin', loadChildren:  './admin/admin.module#AdminModule' }
    ]
  }
];

Admin module route configuration

const _routes: Routes = [
  {
    path: '', component: AdminComponent, children: [
      { path: 'adminPage1', component: adminPage1Component},
      { path: 'adminPage2', component: adminPage2Component},

    ]
  }

];

The admin component has the layout structure.

Problems

  1. I need to load adminModule adminPage1 as default component in router-outlet when adminModule is loaded.
  2. How to navigate via .ts file inside adminModule ?

1条回答
甜甜的少女心
2楼-- · 2019-09-02 06:47

I was able to solve it, if anyone having the same issue, the below way worked.

Admin module route configuration

const _routes: Routes = [
  {
    path: '', component: AdminComponent, children: [
      { path: ' ', component: adminPage1Component},
      { path: 'adminPage1', component: adminPage1Component},
      { path: 'adminPage2', component: adminPage2Component},

    ]
  }
];

by adding a empty path ( { path: ' ', component: adminPage1Component} ) inside the children array loaded the component by default.

further, if you an have element which need to add in a css class when the component is loaded. ex:

 <li routerLink="adminPage1" routerLinkActive="active">
          Admin Page 1
 </li> 

you can do the below to support routerLinkActive

const _routes: Routes = [
  {
    path: '', component: AdminComponent, children: [
      { path: ' ', component: adminPage1Component, redirectTo: 'adminPage1',  pathMatch: 'full'},
      { path: 'adminPage1', component: adminPage1Component},
      { path: 'adminPage2', component: adminPage2Component},

    ]
  }
];

I basically added "redirectTo: 'adminPage1', pathMatch: 'full'" to the empty path.

查看更多
登录 后发表回答