0

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Troyer
  • 6,765
  • 3
  • 34
  • 62

1 Answers1

0

Try this:

<ng-navbar *ngIf="userLogged()"></ng-navbar>

userLogged() { return JSON.parse(localStorage.getItem('currentUser')) };
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
  • The answer points in the wrong direction. One should never use method calls in the template. In this case, the change detection will execute this method on every view update. Instead you should subscribe to the userLoggedIn observable which will emit values from places like actual logIn() and logOut() methods. – Developer Thing Sep 29 '21 at 11:08