Reputation: 45
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-header *ngIf="isUserLoggedIn"></app-header>
<router-outlet></router-outlet>
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
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