Home > Back-end >  Why is Angular loading my root template twice
Why is Angular loading my root template twice

Time:06-06

My root component is loading twice even though I have a separate component for my homepage. I have tried to use different things, such as pathMatch, separate component, etc, but no luck. When I go to /dashboard, it works just fine, but when it loads the page initially (root page), the navbar is loaded twice. I want to avoid that.

My code looks like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { NavbarComponent } from './navbar/navbar.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { RouterModule, Routes } from '@angular/router';
import { RootComponent } from './root/root.component';
import { FeatureDashboardComponent } from '@angular/dashboard';
import { FeatureHomepageComponent } from '@angular/homepage';

const routes: Routes = [
  {
    path: '',
    component: RootComponent,
    pathMatch: 'full',
    children: [
      { 
        path: '',
        component: FeatureHomepageComponent
      }
    ]
  },
  {
    path: 'dashboard',
    component: FeatureDashboardComponent
  },
  {
    path: '**',
    redirectTo: ''
  }
];

@NgModule({
  declarations: [
    NavbarComponent,
    RootComponent
  ],
  imports: [
    BrowserModule,
    NgbModule,
    RouterModule.forRoot(routes)],
  providers: [],
  bootstrap: [RootComponent],
})
export class AppModule {}

And my HTML for RootComponent is:

<angular-navbar></angular-navbar>
<div >
    <router-outlet></router-outlet>
</div>

And navbar is:

<nav >
    <div >
      <a >My App</a>
    </div> 
</nav>

Example in inspect

CodePudding user response:

Instead of calling the router-outlet try to call to the exact component name

CodePudding user response:

This means you have either of two: another <router-outlet></router-outlet> instance or you are instantiating the <angular-navbar></angular-navbar> in another template other than the one you show here. pathMatch has nothing to do here because the ` component is route agnostic, meaning it is a layout component.

  • Related