Search code examples
angulartypescriptangular2-routing

How do I prevent Angular from loading a Component twice?


My Angular app is loading a component twice. Initially, I had <router-outlet></router-outlet> in my component's template and it was working fine but was still giving me these errors:

core.umd.js:3257 EXCEPTION: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'
core.umd.js:3262 ORIGINAL STACKTRACE:
core.umd.js:3263 Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'
zone.js:355 Unhandled Promise rejection: Cannot find primary outlet to load 'AppComponent' ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot find primary outlet to load 'AppComponent'(…) Error: Cannot find primary outlet to load 'AppComponent' 
zone.js:357 Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'

To resolve these errors, I added <router-outlet></router-outlet> to my template. But now my app is loading my component twice.

app.component.ts

import { Component } from '@angular/core';

@Component({
moduleId: module.id
  selector:'body', 
  templateUrl: 'app.component.html', 
  styleUrls: ['app.component.css']
})

export class AppComponent {
  title = 'Doctor Application';
}

app-routing.module.ts

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent }   from './app.component';

const routes: Routes = [
  { path: '', component: AppComponent  },
];

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

export class AppRoutingModule {}

app.component.html

<h1>{{title}}</h1>
<router-outlet></router-outlet>

Solution

  • The AppComponent shouldn't be part of the routing. It's used to bootstrap. That's what the error is about. You're trying to add the AppComponent to the routing, but there's no <router-outlet> for it, because it is the top-level component.