Angular `<router-outlet>` displays the pattern twice

I am using angular4 and trying to create a link to a router. The link to the router works, but the template is displayed 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 {}
+8
source share
4 answers

Your default route points to AppComponent, so your route passes AppComponentinside AppComponent.

Create for this DashboardComponentor HomeComponent. And then do:

{ path: '', component: DashboardComponent }

Update 1:

Like @ GünterZöchbauer, we have to add pathMatch: 'full'for the “empty road the way without children”.

So, we can go with the approach AppComponent(check Gunther's answer):

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

DashboardComponent, .

+16

?

1) , , main.ts, :

platformBrowserDynamic().bootstrapModule(AppModule);

angular AppModule

2) AppModule :

bootstrap: [ AppComponent ]

angular AppComponent. .

3) AppComponent <router-outlet>. , AppComponent <router-outlet>. .

+8

, pathMatch: 'full'

{ path: '', component: AppComponent },

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

@SrAxi.

+6

.

{ path: 'dashboard', loadChildren: 'app/dashboard/dashboard.module#DashboardModule'},

NgModule({
  imports: [
    SharedModule,
    DashboardRoutingModule,
    PipesModule.forRoot()
  ],
  declarations: [
    MyDashboardComponent,
    DashboardParentComponent
  ],
  providers: [
    ApiService
  ],
})
export class DashboardModule { }
0
source

Source: https://habr.com/ru/post/1675262/


All Articles