我正在使用角度4并尝试创建路由器链接。路由器链接有效但两次显示模板。 qazxsw poi
下面是我在组件中的代码:
我的路线:
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
或DashboardComponent
。然后做:
HomeComponent
更新1:
作为@GünterZöchbauer,我们应该为“没有孩子的空路径”添加{ path: '', component: DashboardComponent }
。
所以我们可以采用pathMatch: 'full'
方法(查看Günter的答案):
AppComponent
或者,正如我在上面的回答中所述,{ path: '', component: AppComponent, pathMatch: 'full' }
方法。
为什么会这样?
1)在您的应用程序入口点,很可能是DashboardComponent
,可以读取此行:
main.ts
这告诉angular引导模块AppModule
2)在AppModule中,可以找到以下行:
platformBrowserDynamic().bootstrapModule(AppModule);
这告诉angular引导组件AppComponent。这就是您看到第一个联系人应用程序部分的原因。
3)现在,AppComponent的模板包含bootstrap: [ AppComponent ]
。路由器读取路由配置,相应地实例化AppComponent并在<router-outlet>
之后立即注入它。这就是您看到第二个联系人应用程序部分的原因。
如果您的路径没有子路径,请使用<router-outlet>
代替
pathMatch: 'full'
使用
{ path: '', component: AppComponent },
以及@SrAxi所说的话。
答案对我不起作用。
路线
{ path: '', component: AppComponent, pathMatch: 'full' },
仪表板模块
{ path: 'dashboard', loadChildren: 'app/dashboard/dashboard.module#DashboardModule'},