CodingMole
CodingMole

Reputation: 53

Show / Hide menu bar dynamically in Angular 2

I'm currently working on a Angular 2 project. I implemented two components (1. header and 2. display page content). If I open the service, I start with login / register. At this time, I want to hide all other menu items. If I'm logged-in, I want to show all menu items.

Currently, I'm using *ngIf to show and hide the the menu items, what actually works. My problem is, that if I start the page and I'm not logged-in, the menu items aren't there (this is fine). However, if I login, just the container with the page content is changing the content and not the menu bar...

Currently, I check if I'm logged in or not in this way:

<div *ngIf="user != null">
...menu items...
</div>

This works if I reload the whole page - but I think there should be a nicer way to display / hide the menu items in real time without manual refreshing?

Could you kindly help me how I can solve this issue?

Upvotes: 2

Views: 1608

Answers (1)

Zhen Lu
Zhen Lu

Reputation: 26

You should probably create a global user service which tracks user state and that components can subscribe to in order to always have a real time updates regarding where the user is logged in or not.

If you don't like the ngif solution at that point, you have a few options: you can create an entirely new component and display that in a route that is only accessible when the user is logged in, or you can do something like create a menu items array that controls your navigation menu items and run an ngfor.

Questions you should answer for more help are things like where are you currently tracking user state (your user variable) and how are components being notified of this variable changing? Just by guessing, you are probably setting the user variable based on local storage in a constructor or oninit function in your header and then leaving it. This will cause it to get the value of user one time but not update it later, which is why it will properly display on page refresh.

Upvotes: 1

Related Questions