Search code examples
angulartypescriptheadershow-hide

Header should hide if no user logged-in in angular 4


My requirement is to hide an Header if no user logged-in in angular 4 application.

I'm trying to implement it in app.component.html and app.component.ts

app.component.html

<app-header *ngIf="isUserLoggedIn"></app-header>
<router-outlet></router-outlet>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from './services/authentication.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
  title = 'app';
  public isUserLoggedIn: boolean;

  constructor(private authService: AuthenticationService) {}

  ngOnInit() {
      this.isUserLoggedIn = this.authService.isUserLoggedIn(); // returns true if user logged-in otherwise returns false
      console.log(this.isUserLoggedIn);
  }

}

above code is working only if page get refreshed and not working whenever url path changed without refresh. Any thoughts/alternate-ideas please?


Solution

  • ngOnInit gets called only once during the component gets initialized so it works when you refresh the page.

    Inorder to make it work , make a function and return it inside

     isLoggedIn(): boolean {
         return this.authService.isUserLoggedIn();
     }
    

    and HTML

    <app-header *ngIf="isLoggedIn()"></app-header>