如何在Angular 6 Cli项目中为第二个根组件定义路线

时间:2018-07-03 11:00:21

标签: angular

有人可以告诉我如何在root components + Angular6项目中为多个angular-cli分别定义路由吗?

当前,我有两个根组件AppComponentLoginComponent,我正在这样做以加载它们:

index.html

<body>
  <app-root></app-root>
  <app-login></app-login>
</body>

app.module.ts

@NgModule({
    ...
    bootstrap: [AppComponent, LoginComponent]
})

我有两个查询:

  1. 如何为第二个根组件定义路由
  2. 如何根据路由选择加载任何根组件?

示例:如果我转到/login/login/conf1,则仅应加载LoginComponent。对于其他路线AppComponent

令人惊讶的是,网络上没有关于多个根组件的教程,或者至少我找不到一个。

我的两个组件用例:Link

2 个答案:

答案 0 :(得分:0)

您应保持AppComponent不变,并创建另一个组件来处理路线

您应该拥有AppComponent,LoginComponent和AnotherOneComponent

在app.module.ts

@ngModule({
   imports: [
     RouterModule.forRoot(routes)
   ]
})

export const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '**',
    component: AnotherOneComponent
  }
];

在app.component.html

<router-outlet></router-outlet>

如果您想处理某事

/login/conf1

您将需要定义子路线

答案 1 :(得分:0)

  1. 如果要将子路由用作路由,可以执行以下操作:

    export const routes: Routes = [ { path: 'login', component: LoginComponent, children: [ { path: 'one', component: SomeComponent}, { path: 'two', component: SomeOtherComponent } ] } ];

  2. 如果要基于路由动态加载组件,可以将路由器模块插入app.component.ts文件中

constructor(private router: Router){}

,然后在html中:

`
<app-login *ngIf="router.url != '/login' ></app-login>
`