角度`< router-outlet>``两次显示模板 [英] Angular `<router-outlet>` displays template twice
问题描述
我正在使用angular4并尝试创建路由器链接.路由器链接有效,但显示两次模板.
I'm using angular4 and trying to create a router link. The router link works but displays the template twice.
下面是我在组件中的代码:
Below is my code in the component:
import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
template: `
<h1>Contacts App</h1>
<ul>
<li><a [routerLink]="['/facebook/top']">Contact List</a></li>
</ul>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor(
private route: ActivatedRoute,
private router: Router,
){ }
gotoDetail(): void {
this.router.navigate(['facebook/top']);
}
}
我的路线:
const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'facebook/top', component: CommentComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
推荐答案
您的默认路线指向AppComponent
,因此您的路线是在AppComponent
内部呈现AppComponent
.
Your default route points to AppComponent
, so your route is rendering the AppComponent
inside the AppComponent
.
为此创建一个DashboardComponent
或HomeComponent
.然后执行:
Create a DashboardComponent
or HomeComponent
for this. And then do:
{ path: '', component: DashboardComponent }
更新1:
如@GünterZöchbauer所述,我们应为没有孩子的空路径路线"添加pathMatch: 'full'
..
As @GünterZöchbauer mentioned, we should add pathMatch: 'full'
for "an empty path route with no children".
所以我们可以采用AppComponent
方法(检查昆特的答案):
So we can go with the AppComponent
approach (check Günter's answer):
{ path: '', component: AppComponent, pathMatch: 'full' }
或者,正如我在回答中所述的DashboardComponent
方法.
Or, the DashboardComponent
approach as I stated above in my answer.
这篇关于角度`< router-outlet>``两次显示模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!