角度`< router-outlet>``两次显示模板 [英] Angular `<router-outlet>` displays template twice

查看:119
本文介绍了角度`< router-outlet>``两次显示模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

为此创建一个DashboardComponentHomeComponent.然后执行:

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.

这篇关于角度`&lt; router-outlet&gt;``两次显示模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆