这是我主页的标记。我写了几条路线,切换到它们时需要显示相应组件的内容而不是主页。我从家的底部添加了它,并且继续显示家庭内容。
<div class="container">
<div class="row">
<app-header></app-header>
</div>
<div class="row">
<app-home></app-home>
<router-outlet></router-outlet>
</div>
<div class="row">
<app-footer></app-footer>
</div>
</div>
这是我的应用程序主页:
<app-home-news [homeImages]="homeImages"></app-home-news>
<router-outlet></router-outlet>
这是我的路线:
const routes: Routes = [
{ path: 'sign-up', component: SignUpComponent },
{ path: 'sign-in', component: SignInComponent }
];
没有错误,内容只是添加到家中。如何让它出现在他的位置上?
看到任何在<router-outlet></router-outlet>
之外的东西都会永远存在。就像你的情况一样,header
和footer
应该只在主html中,而不是home
组件中。在路由的基础上更改的任何内容,都应该是路由配置的一部分。
进行以下更改
<div class="container">
<div class="row">
<app-header></app-header>
</div>
<div class="row">
<!-- removed the home component -->
<router-outlet></router-outlet>
</div>
<div class="row">
<app-footer></app-footer>
</div>
</div>
将主组件添加为路由的一部分。
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'sign-up', component: SignUpComponent },
{ path: 'sign-in', component: SignInComponent }
];
注意:我在根级别添加组件,因此我将路径留空,但您可以根据您的路径,例如
{ path: 'home', component: HomeComponent },
您需要注意您的路由以及您的 url 将填充的路由器插座。这不仅仅是在每个组件的底部放置一个路由器插座以显示新内容的情况......
假设我有一个非常基本的AppComponent
模板:
<h1>Hello</h1>
<router-outlet></router-outlet>
。和一些配置的路由:
{ path: '', component: HomeComponent }
{ path: 'test', component: TestComponent },
{ path: 'hello', component: HelloComponent}
。它只是在 p 标签中包含自己的名字(分别为 home、test 和 hello(。
对于每个 url,情况如下:example.com
你好
家
example.com/test
你好
测试
example.com/hello
你好
你好
路由已将组件加载到路由器插座中。
如果我的组件当时有自己的路由器插座,我们就进入了子路由领域,其中您开始使用 url,例如example.com/test/abc
,您的路由看起来更像:
{
path: 'test',
component: TestComponent,
children: [
{ path: 'abc', component: AbcComponent },
{ path: 'def', component: DefComponent }
]
}
这将导致 - 假设与上述相同的内容规则如下所示:
example.com/test/abc
:
你好
测试
美国广播公司
example.com/test/def
:
你好
测试
定义
通常,您的AppComponent
使用单个router-outlet
处理站点范围的页眉/页脚/导航/等,所有其他组件都将加载到其中,其中包括您的主页本身......
{ path: '', component: HomeComponent }
{ path: 'sign-up', component: SignupComponent }
{ path: 'sign-in', component: SigninComponent }
组件中很可能有更多的路由器插座(如上所述(,但似乎您当前想要的很可能是这种情况,而不是您当前拥有的具有嵌套插座的更复杂的类型。