Search⌘ K

Toggling Menu Items

Explore how to dynamically toggle menu items in an Angular application by injecting an authentication service. Understand the use of ngIf with else blocks and ng-template to conditionally display login, register, secret page, or logout links depending on whether the user is logged in or not.

We’ve updated the service to store the user’s current authentication status. It will always know if the user is logged in, even if we refresh the app. The service is injectable, meaning it can be used in any component that needs it.

Let’s use it to toggle the menu items in the header. It doesn’t make sense to show the login and register links if the user is already logged in. Let’s show them links to view the secret page or log out.

Injecting the service

The menu is rendered in the App component. We’ll need to inject the authentication service into it. Update the app.component.ts component class file to the following:

TypeScript 3.3.4
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public authService: AuthService) { }
}

On line 2, we’re importing the AuthService class into the ...