问题描述
限时送ChatGPT账号..我正在使用 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
应用组件
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
方法(查看 Günter 的回答):
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.
这篇关于Angular `<router-outlet>` 显示模板两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论