Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Angular 2 render app component template twice

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....

like image 701
Stacy J Avatar asked Sep 12 '17 19:09

Stacy J


People also ask

Why is ngOnInit called twice?

Why it is called twice. Right now, if an error happens during detecting changes of content/view children of a component, ngOnInit will be called twice (seen in DynamicChangeDetector). This can lead to follow up errors that hide the original error.

How does angular render a component?

Angular gives us the mechanism to render components dynamically through View Container using ComponentFactory. To do this, we need to know the Component Type at the compile time. The most dynamic component rendering mechanism would be the one where we don't know what component will be rendered at the compile time.

What is component template in angular?

A template is an HTML snippet that tells Angular how to render the component in angular application. The template is immediately associated with a component defines that component's view.


Video Answer


1 Answers

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.

like image 167
JB Nizet Avatar answered Oct 23 '22 15:10

JB Nizet