javascriptangularjsangularjs-ng-if

Angularjs 4 - Need to refresh for display/hide directive


I have a problem to hide the navbar when the user is not logged in (on the public views), I check if the item currentUser exists on the localStorage and then I use *ngIf on the html template to show/hide.

When I login at first I don't see the navbar, but after refreshing the page it's displaying, the same when I logout, at first it shows it and after refreshing the page it's gone.

There is my app.component.ts

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

@Component({
    moduleId: module.id,
    selector: 'app',
    templateUrl: 'app.component.html'
})

export class AppComponent implements OnInit {

    userLogged = JSON.parse(localStorage.getItem('currentUser'));

    ngOnInit() {
        console.log(this.userLogged);

    }

}

And my app.component.html

<!-- main app container -->
<div class="jumbotron">
    <div class="container">
        <ng-navbar *ngIf="userLogged"></ng-navbar>
        <div class="col-sm-12">
            <alert></alert>
            <router-outlet></router-outlet>
        </div>
    </div>
</div>

In case you need more information just ask for it, is my first Angularjs 4 question and I don't know what to show exactly.


Solution

  • Try this:

    <ng-navbar *ngIf="userLogged()"></ng-navbar>
    
    userLogged() { return JSON.parse(localStorage.getItem('currentUser')) };