Home > Blockchain >  Split Angular component
Split Angular component

Time:10-21

I have pages in Angular that have a header, a side bar and a main content page. Depending on the the route, the main content changes while the header and the side bar stay pretty much the same. There should be only small changes so it makes sense to create the page outlet centrally. So I have something like:

app.component.html:

<header>...</header>
<nav>...</nav
<main><router-outlet></router-outlet></main>

But for some pages I also want to adjust the header and side bar. Is there a possibility to do something like:

app.component.html:

<header>...<router-outlet #1></router-outlet></header>
<nav>...<router-outlet #2></router-outlet></nav
<main><router-outlet #3></router-outlet></main>

page1.component.html

<content #1><a>Login</a></content>
<content #3>...</content>

so I can optionally add content at multiple places in the root?

CodePudding user response:

If you want to show dynamic header and footer, I would suggest you to pass configuration to your header component using @Input. The reason we divide our features or functionalities in form of components, directives or modules, are to make them configurable.

Instead of marking router-outlet with local variable, you should pass the configuration to the header component similarly for nav bar.

so I can optionally add content at multiple places in the root?

You can use the content projection in the component and you can make it dynamic based on the need for your component you want to show.

CodePudding user response:

I also suggest not using router-outlet. If your header and side nav need to change significantly then declaring the nav and header within that the component that is rendered by the router-outlet and then using @Input (docs here) is an option. @Input could be used to input the values you want displayed in the header and nav components and you can interpolate them onto the template or to use as a string/other value to show different versions of the two components.

E.g.

app.component.html

<router-outlet></router-outlet>

one-of-your-pages.component.html (that gets rendered in your router-outlet

<app-header version="one"></app-header>
<app-nav version="one"></app-nav>
<div>
    // Page content here
</div>

Then within one of the reusable components e.g. the header

header.component.ts

...
export class HeaderComponent {
   @Input() version: any;

   ...
}

header.component.html

...
<div *ngIf="version === 'one'; else elseBlock">
   // Some content here
</div>
<ng-template #elseBlock>
<div> //Some other content </div>
</ng-template>
...
  • Related