我在angular中构建一个nav组件,允许用户转到App.component中的组件。此导航组件也位于App组件内。所有组件都从头开始显示,我希望导航器能够找到已在App组件中显示的组件。
我试图将导航在App组件硬编码中,但它没有用。
这是我的App.component.html,我调用所有组件,这是父组件。
<app-slideshow></app-slideshow>
<!--others-->
<app-dashboard></app-dashboard> //<-- component where the nav is
<router-outlet></router-outlet>
这是我的app-routing.module.ts,其中我定义了组件的路由
const parentModuleRoutes: Routes = [
{
path: 'home', //<---- parent component declared here
component: AppComponent,
children: [ //<---- child components
declared here
{
path:'slideshow',
component: SlideshowComponent
},
{
path:'about',
component: AboutComponent
},
{
path:'service',
component: ServiceComponent
},
{
path:'explore',
component: WorksComponent
},
{
path:'contact',
component: ContactComponent
},
]
}
];
这是构建nav元素的仪表板组件,以及我想用组件创建链接的位置
<nav>
<ul>
<li>
<a routerLink="/home/slideshow">
<p>Home</p>
</a>
</li>
<li>
<a routerLink="/home/about">
<p>About Us</p>
</a>
</li>
<li>
<a routerLink="/home/service">
<p>Service</p>
</a>
</li>
<li>
<a routerLink="/home/explore">
<p>Explore</p>
</a>
</li>
<li>
<a routerLink="/home/contact">
<p>Contact Us</p>
</a>
</li>
</ul>
</nav>
控制台打印出这三个错误,因为路由器插座是在app组件(父级)上定义的:
ERROR Error: StaticInjectorError(AppModule)[RouterOutlet ->
ChildrenOutletContexts]:
StaticInjectorError(Platform: core)[RouterOutlet ->
ChildrenOutletContexts]:
NullInjectorError: No provider for ChildrenOutletContexts!
ERROR CONTEXT DebugContext_
View_AppComponent_0 @ AppComponent.html:16
Error: StaticInjectorError(AppModule)[RouterOutlet ->
ChildrenOutletContexts]:
StaticInjectorError(Platform: core)[RouterOutlet ->
ChildrenOutletContexts]:
NullInjectorError: No provider for ChildrenOutletContexts!
诀窍是创建布局组件并在app.component中调用它,所以当你想用导航栏更改为另一个组件时,你可以使用它转到/ about或/ service,同时更改布局的其余部分。
App.component.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
APP-routing.module.ts
const parentModuleRoutes: Routes = [
{
path:'slideshow',
component: SlideshowComponent
},
{
path:'about',
component: AboutComponent
},
{
path:'service',
component: ServiceComponent
},
{
path:'explore',
component: WorksComponent
},
{
path:'contact',
component: ContactComponent
}
];