5.1: Dropdown Functionality

Right now, our dropdown isn't working and we're simply logging the user out when a clicking on their welcome message. Let's fix that!

We'll use the ngx-bootstrap library that we added to our project earlier. Read the documentation if you'd like to learn more or customize it.

Import ngx-bootsrap Dropdown Module

In your app.module.ts file - import the BsDropdownModule and add it to the imports array:

import { BsDropdownModule } from 'ngx-bootstrap';

//  ...

imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes),
    BsDropdownModule.forRoot(),

//  ...

Add to the Nav Template

In nav.component.html, update the div containing the dropdown to the following:

We'll also update the nav.component.scss file to make the cursor a pointer when hovered over the element:

.dropdown {
    cursor: pointer;
}

Redirect the User to Members Page After Login

Right now, when our users login - they stay at the home page. But, it would be better if we directed them to the list of users.

In nav.component.ts, inject Router into the component:

constructor(
    public authService: AuthService,
    private _router: Router) { }

Next, modify the login() method to redirect after completion:

login() {
this.authService.login(this.model).subscribe(data => {
    console.log('logged in successfully');
    }, error => {
        console.log('Failed to login');
    }, () => {                                              // <---- ADDED
        this._router.navigate(['members']);
    });
}

Open the browser and verify that you are being redirected when you login.

Redirect the User to Home Page After Logout

Similarly, we'll redirect the user after logging out to the home page

Update the logout() method in nav.component.ts:

logout() {
    this.authService.userToken = null;
    localStorage.removeItem('token');
    console.log('logged out');
    this._router.navigate(['/home']);
}

Last updated