user2388677
user2388677

Reputation: 45

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?

Upvotes: 2

Views: 1236

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222672

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>

Upvotes: 1

Related Questions