Search code examples
angularangular2-routingangular2-componentsangular2-modules

Working with layouts in Angular2 app


I have developed an Angular2 app using routing.

My problem scenario is:

I have a Login page which has different HTML and CSS.Once successfully logged in, I redirect to another page which has different HTML and CSS. But I have index.html(login page) as my main layout. Hence I need to understand how to work with multiple layouts?

I have done some R&D but I am not able to understand how to implement it?

Please find below code:

1) app.routing.module

import { NgModule } from '@angular/core';
import { Routes, Router, RouterModule } from '@angular/router';
import { AuthGuard } from './guards/auth.guard';
import { LoginComponent } from './components/login/login.component';

const routes: Routes = [
{
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
},
{
    path: 'login',
    component: LoginComponent
},
{
    path: 'employee',
    component: EmployeeComponent,
    canActivate: [AuthGuard]
}];
export class AppRoutingModule {   }
export const routedComponents = [LoginComponent,EmployeeComponent];

2) App component

import { Component} from '@angular/core';
@Component({
           selector: 'my-app',
           template: `
          <router-outlet></router-outlet>
          `
          })
export class AppComponent {
        constructor() {
        }
}

3) App module

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {HttpModule} from '@angular/http';
import { AppComponent }   from './app.component';
import { AppRoutingModule, routedComponents } from './app-routing.module';
import { AuthGuard } from './guards/auth.guard';


 @NgModule({
     imports: [BrowserModule,
               HttpModule,
               AppRoutingModule
      ],
     declarations: [AppComponent,
                    routedComponents
     ],
     providers: [AuthGuard],
     bootstrap: [AppComponent]

    })
 export class AppModule { }

4) Index.html

 <my-app>

 </my-app>

Any help would be highly appreciable!

Thanks!!


Solution

    • Remove all CSS from index.html and create separate component for login and another component say home for other features.
    • Load CSS for login and home in login component and home component respectively.
    • Create separate routes for login and home,place all other features routes inside home route as child route. Please find below code:

      {
      path: 'login',
      component: LoginComponent
      },
      {
        path: 'home',
        component: HomeComponent,
        children: [
             {
              path: 'childPage',
              component: childPageComponent
             }]
      }
      
    • Use below line to navigate to child page:

      this.router.navigate(['/home/childPage'])
      

    Thanks!!!