Angular `<router-outlet>` displays template twice

kevinabraham picture kevinabraham · Apr 20, 2017 · Viewed 12.2k times · Source

I'm using angular4 and trying to create a router link. The router link works but displays the template twice. duplicate component

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']);
    }
}

my routes:

const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'facebook/top',  component: CommentComponent },
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

Answer

SrAxi picture SrAxi · Apr 20, 2017

Your default route points to AppComponent, so your route is rendering the AppComponent inside the AppComponent.

Create a DashboardComponent or HomeComponent for this. And then do:

{ path: '', component: DashboardComponent }

Update 1:

As @GünterZöchbauer mentioned, we should add pathMatch: 'full' for "an empty path route with no children".

So we can go with the AppComponent approach (check Günter's answer):

{ path: '', component: AppComponent, pathMatch: 'full' }

Or, the DashboardComponent approach as I stated above in my answer.