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

查看:20
本文介绍了Angular `<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应用组件.

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 方法(查看 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 `&lt;router-outlet&gt;` 显示模板两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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