Why does Angular 2 render app component template twice

10.6k views Asked by At

I want to display common header and footer throughout my app. But when I try to do it, it gets displayed twice :-

app.component.html

<header>
    Header
</header>
<router-outlet></router-outlet>
<footer>
    Footer
</footer>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

app.module.ts

RouterModule.forRoot([
  {path: 'home', component: AppComponent},
  {path: '*', redirectTo: 'home', pathMatch: 'full'},
  {path: '**', redirectTo: 'home', pathMatch: 'full'}
])

Result

Header
Header
Footer
Footer

Last time I solved this problem by creating components for header and footer. I know it will work if I do the same, but I want to understand why this is wrong....

2

There are 2 answers

2
JB Nizet On BEST ANSWER

Because the App component is the root component of your application, which is always there, and is also the component displayed, inside this root component, by the router outlet, for the 'home' path. So you're saying the router to display the app component inside the app component.

Create a real, different home component. Don't reuse the root component for your home page.

0
futbolsalas15 On

The following happened to me, in the context of transforming Angular Components into Web Components (if you or other readers could feel identified by this specific use case):

Another reason why Angular Component is rendering twice is that you maybe are registering the component as a web component (using @angular/elements package) and, at the same time, you are using the same component as angular component.

For example, if you have an angular component (e.g. <simple-title>) that you are using inside another angular component (e.g. <complex-title>), and you also registered the first component as web component (e.g. createCustomElement(<simple-title>)), then the second component (<complex-title>) could take the angular version and the web component version of the component as valid and, then, render twice.

The solution (in my case) was create another angular component that could be reused by both components (e.g. <title-renderer> that is used by <simple-title> and <complex-title>).