3.3: NavBar Login Toggle

Adding Welcome Message

When our user is logged in, let's display a welcome message with a dropdown.

In your nav.component.html file - underneath the login form, add the following:

</form>

<!-- add here -->
<div class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Welcome, user!
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        <a class="dropdown-item" href="#"><i class="fa fa-user"></i>Edit Profile</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#"><i class="fa fa-sign-out"></i>Logout</a>
    </div>
</div>

Add this to the nav.component.scss file:

#navbarDropdown {
    color: white;
}

Note: our dropdown doesn't work yet. It's because we aren't using jQuery. But, don't worry about it - we'll fix it!

Adding *ngIf Directive to our Form and Welcome div

In the <form> tag encompassing the login form add an ngIf statement to display the element if not logged in:

Next, in the <div> encompassing the Welcome dropdown add the opposite ngIf to display the element if the user is logged in.

Until we get our dropdown menu working, let's also add a click listener that will log us out when we click on our welcome message.

Adding the logout() and loggedIn Methods

In our nav.component.ts file - add the following methods:

And, add the loggedIn() method to auth.service.ts:

Right now, the loggedIn() method isn't very secure. All it is doing is checking whether there is an item in localStorage called 'token.' It's not necessarily valid and it may have expired! We'll improve it later.

Open up the browser and verify that the navbar is toggling between the login for and the welcome message depending on whether you are logged in or not.

Last updated