Heena
Heena

Reputation: 1773

How to display menu bar only after log in?

I am trying to implement a simple application in Angular 2 .I created a login and home components which includes html and .ts files.

I created a routing.ts file which routes my components.

I also included a header.component.ts and header.component.html which implements the menu bar of my application.

But Iam getting my menu bar in both the components and when loading my default login page also.

Below shown is my code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { routing } from "./app.routing";
import { LoginComponent } from './login/login.component';
import { RouterModule, Routes} from '@angular/router';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [ AppComponent, HeaderComponent, LoginComponent, 
HomeComponent],

  imports: [ RouterModule, BrowserModule, routing  ],

  providers: [],

  bootstrap: [AppComponent]
 })
 export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
 })
export class AppComponent {
  title = '';
}

app.component.html

 <div style="text-align:justify-all;">
  <h1>
    {{title}}
  </h1>

 <div class="container">
 <app-header></app-header>
     <hr>
 <router-outlet></router-outlet>
 </div>

app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent },
];
export const routing = RouterModule.forRoot(APP_ROUTES);

header.component.html

 <div class="row">
 <div class="col-xs-12"><ul class="nav nav-pills">
    <li routerLinkActive="active"><a [routerLink]="['/home']">
 <strong>Home</strong></a></li>
    <li><a [routerLink]="['/login']"><strong>Logout</strong></a></li>
    </ul></div>
 </div>

header.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',

})
export class HeaderComponent {
 }

Here is my login component

login.component.html

  <div class="container formWidth" style="text-align:left;">
    <h1> eSpace Login</h1>
<br/>
   <form (submit)="loginUser($event)">
    <div class="form-group">
      <label for="Username">Username:</label>
      <input type="Username"  id="Username" placeholder="Enter Username" 
name="Username">
    </div>
    <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password"  id="pwd" placeholder="Enter password" 
name="pwd">
    </div>

    <br/>
       <button type="submit" class="btn btn-default">Submit</button>
  </form>

</div>

login.component.ts

import { Component, OnInit } from '@angular/core';
 import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})
export class LoginComponent implements OnInit {

  constructor(private router:Router ) {
   } 
  ngOnInit() {
  }

loginUser(e){
e.preventDefault();
 console.log(e);
    var username=e.target.elements[0].value;
    var password=e.target.elements[1].value;

    if (username == 'heena' && password == 'mille' )  
    this.router.navigate(['home']);
}
}

Here is my home component

home.component.ts

import { Component, OnInit } from '@angular/core';

 @Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

home.component.html

     <p> <strong> Welcome to eSpace Home </strong></p>

    <img src="/../../assets/i9.jpeg" class="img-rounded" alt="home" 
     height="400" width="1150">

can anybody please suggest me the logic how to display the menu bar in my home page and not in my login page after my login ,since many views are loading in one page ?

Upvotes: 1

Views: 8751

Answers (3)

Harshil Parekh
Harshil Parekh

Reputation: 166

I have faced problem of not changing "IsLoggedIn" status from auth Service. So added EventEmitter property in service.

In my functionality, Every time when Page Loads, it checks the user from cache, and it is there I am emitting event, which is bounded to my Header component.

Here is the code in Service:

export class TokenStorageService { 
    @Output() SendLogInStatusEvent = new EventEmitter<boolean>();   //  Event Emitter Property

   // Function definition which emits the event

    SendIsLoggedInStatus(IsLoggedIn: boolean) {
      this.SendLogInStatusEvent.emit(IsLoggedIn);
    }

  public getUser() : IUserInfo {
    let User = JSON.parse(sessionStorage.getItem(USER_KEY));
    let token = sessionStorage.getItem(TOKEN_KEY);
    if (User && token){
      this.SendIsLoggedInStatus(true);    // Calling Function to emit the data!
    }
    return User;
  }
}

Now in header component, just need to grab the change of Log-In status:

IsLoggedIn : boolean; // property for log in status

ngOnInit(): void {  
   this._TokenStorageService.SendLogInStatusEvent
    .subscribe((data:boolean) => {
      this.IsLoggedIn = data;
  });
};

you can use this property in your nav component with *ngIf directive to show and hide your LogIn/LogOut or any Link.

Upvotes: 0

BeetleJuice
BeetleJuice

Reputation: 40896

@LLai's solution (nested routes that all show the menu) is great. Here is another that can be implemented really quickly:

If you want the menu to be hidden when the user is not logged in, the quickest fix might be to update your HeaderComponent with an *ngIf guard that shows the component only once the user is logged in:

export class HeaderComponent {
  // update with your regular way of checking whether the user is logged in
  isUserLoggedIn = false;
}

HeaderComponent template:

<ng-container *ngIf="isUserLoggedIn">
  <!-- put your regular template here -->
</ng-container>

You could also put this guard in the parent AppComponent template; this way the HeaderComponent won't even load until the users login, thus saving some resources.

Upvotes: 1

LLai
LLai

Reputation: 13396

You could create a new dashboard component that uses a nested router-outlet so the menu bar only appears on a subset of routes.

// app.module.ts
const APP_ROUTES: Routes = [
    { path: '' , redirectTo: '/login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { 
        path: 'dashboard',
        component: 'DashboardLayoutComponent',
        children : [
            { path: 'home', component: HomeComponent },
            { path: 'collection', component: CollectionComponent },
            { path: 'market', component: MarketComponent }
        ]
    }
];

So include your menu bar within the dashboard layout component

// dashboard-layout.component.html
<div style="text-align:justify-all;">
    <h1>
        {{title}}
    </h1>
<div class="container">
    <app-header></app-header>
    <hr>
    <router-outlet></router-outlet>
</div>

And reduce your app.component.html to just a router-outlet so the menu bar is not included for the login route

// app.component.html
<router-outlet></router-outlet>

Upvotes: 2

Related Questions