Angular 2: Multiple layout files using interpolation

10,791

Solution 1

I worked out what I was trying to achieve by using transclusion... as far as I can see this isn't mentioned anywhere in the official docs!

It's simply a case of using <ng-content></ng-content> in the layout files where the main content for each layout needs to go.

// eg: app-layout.html
<app-header></app-header>
<app-navbar></app-navbar>
// content using this layout will appear below
<ng-content></ng-content>
<app-footer></app-footer>

Then after importing and including in directives use the layout it in a view like

// eg: dashboard.html
<app-layout>
  <h1>Hello {{user}}!</h1>
</app-layout>

Hope this helps someone trying to achieve the same thing

Solution 2

I recommend you to switch your view with different routes, i.e., one route for the logged in users that resolves to a component A and another route for users that aren't logged in that resolves to a component B.

I prefer to use this strategy because you can block users in the route level using the CanActivate hook, i.e., before going to a particular route, there's a validation. If it's false, the user won't access that route. If it's true, the route is activated.

You can read the awesome documentation about how to use the CanActivate here in the Routing & Navigation: CanActivate Guard documentation.

Hope it helps.

Share:
10,791
markstewie
Author by

markstewie

Web, Mobile and App developer and designer living in Auckland, New Zealand

Updated on June 08, 2022

Comments

  • markstewie
    markstewie almost 2 years

    I'm building an Angular 2 app and need two layout files. One for the logged out users... (Login/Register views etc) and one for the logged in users to see the actual app itself. How can this be achieved with Angular 2?

    Currently I have an app.component.html that simply has

    <main-navbar></main-navbar>
    <router-outlet></router-outlet>
    

    But what I need to do is something along the lines of:

    <div [ngSwitch]="layout">
    
      <template [ngSwitchCase]="panelLayout">
          /* output all the html layout elements for the logged out views */
          <router-outlet></router-outlet>
      <template>
    
      <template [ngSwitchCase]="appLayout">
         /* output all the html elements for the in logged in/app views */
         <router-outlet></router-outlet>
      </template>
    
    </div>
    

    But I have no idea where or how to set the layout variable.

    I'm presuming this variable would best be set inside the main view component... or is there a better way to do this?