Search code examples
angularrouter-outlet

Is the <router-outlet> activating my component which I did not write a tag for?


I'm currently reading through the code on the Angular getting started docs: https://angular.io/generated/live-examples/getting-started-v0/stackblitz.html

I see how in app.component.html, the top-bar.component is being rendered because of <app-top-bar></app-top-bar>. However, I don't see where the product-list.component is being rendered. The only option I see is by the <router-outlet></router-outlet>.

In the Router Outlet Docs, it says:

A router outlet will emit an activate event any time a new component is being instantiated, and a deactivate event when it is being destroyed.

Does this mean that the router outlet is activating the product-list.component once it is instantiated, causing it to be rendered on the screen? If so, why is the top bar being left outside of the router outlet? Why not just let the router outlet activate the top bar?

Here is app.component.html:

<app-top-bar></app-top-bar>

<div class="container">
  <router-outlet></router-outlet>
</div>

Solution

  • There are two different ways that you can call "html" to your principal page (app.component.html).

    The first one is to put the "html" in your index and you can't change that, you will see always that page.

    In your component you have something like this code:

    @Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.css']
    })
    

    You have tu use "selector" for call in your html:

    <app-header></app-header>
    

    router-outlet is to use a single tag so you can change HTML depending on the routes.

    In app-module you need to import product-list.component, for example:

    import { HeaderComponent } from './header/header.component';
    

    An then you must define the routes in a variable:

    const routes: Routes= [
    {path: '', redirectTo:'/clientes', pathMatch: 'full'},
    {path: 'product', component: NameComponent}];