我正在为我创建一个入门项目。我需要做的是创建一个组件,在其中调用导航栏、侧边栏、页脚和一个我想显示为路由器的页面。
这是我的应用程序。路由
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LayoutComponent } from './layout/layout.component';
import { LoginComponent } from './screens/auth/login/login.component';
import { StatsComponent } from './screens/stats/stats.component';
const appRoutes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'Dashboard', component: LayoutComponent },
{ path: 'login', component: LoginComponent },
{ path: 'stats', component: StatsComponent }
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我有一个简单的登录页面,通过它我可以进入仪表板路由
<h1>Angular Router App</h1>
<nav>
<ul>
<li><a routerLink="/Dashboard/login" routerLinkActive="active">Login</a></li>
</ul>
</nav>
这是我的LayoutComponent(仪表板)
<div class="wrapper">
<div class="app-sidebar" data-active-color="white" data-background-color="black" data-image="assets/img/sidebar-bg/01.jpg">
<p>Sidebar</p>
<div class="sidebar-background"></div>
</div>
<!-- <app-navbar></app-navbar> -->
<p>NavBar</p>
<div class="main-panel">
<div class="main-content">
<div class="content-wrapper">
<div class="container-fluid">
<router-outlet></router-outlet>
</div>
</div>
</div>
<!-- <app-footer></app-footer> -->
<p>Footer</p>
</div>
</div>
您可以看到我在此页面上有
<router-outlet></router-outlet>
,我需要知道如何在其中显示另一个组件?我有一个关于应用程序路由的组件 stats
。我是否需要在该布局中显示该组件,如何将其显示为路由?
意思是类似
Dashboard/stats
当您想在项目中使用路由时,您应该按如下方式创建项目:
ng new my-project --routing=true
这将创建一个您需要的路由文件,即
app-routing.module.ts
现在创建路线:
ng generate module routes/route-1 --routing=true
这将创建新文件,特别是:
route-1.module.ts
route-1-routing.module.ts
在
route-1-routing.module.ts
中定义路由,如下所示:
const routes: Routes = [
{ path: '', component: Route1Component },
{ path: 'hello', component: HelloComponent }
]
(显然,使用
ng g c routes/route-1/components/route-1
和 ng g c routes/route-1/components/hello
之类的东西创建这些组件 - 这些命令在命令行上执行,就像使用 ng new 命令时一样)
现在回到 app-routing.module.ts 添加以下内容:
const routes: Routes = [
{
path: 'route-1',
loadChildren: () => import('./routes/route-1/route-1.module').then(m => m.Route1Module)
}
]
现在您可以访问:
在浏览器中输入/route-1
,您将看到 Route1Component(其中 <router-outlet></router-outlet>
是 - 不要忘记在 app.component.html 中添加 router-outlet
)
您可以访问:
在浏览器中输入/route-1/hello
,您将看到 HelloComponent(同样是 router-outlet
所在的位置)
最后,您可以使用
创建路线链接<a routerLink="/route-1">route-1</a>
<a routerLink="/route-1/hello">route-1/hello</a>
重复此过程以添加更多路线。