Rahul Sharma
Rahul Sharma

Reputation: 35

How to hide the Navigation bar buttons of Header Component from routing in Angular 8?

How can i hide / show the navigation bar buttons while navigating to login page .

Ex- In my App component I have Header Component , Router Outlet & Footer Component In my Header Component I have around 5 Navigation buttons ex - Login, Registration , About , Contact US etc. Now, what I want is if someone clicks Login So, Login form is there and when someone logged in and moved to Dashboard page the Header should not contain Login and Registration options .

Ex- Notifying the header page again . Below is my code -

AppComponent.html

 <app-header></app-header>

 <router-outlet></router-outlet>

 <app-footer></app-footer>

app-routing.module.ts

const routes: Routes = [
      { path: '', component: HomeComponent },
      {path:'registration', component: RegistrationComponent},
      {path: 'login', component: LoginComponent},
      {path: 'dashboard', component: DashboardComponent},
      {path: 'header', component: HeaderComponent},
    ];

HeaderComponent.html

<div class="navbar-nav ml-auto">

            <a class="nav-item nav-link" routerLink="/login"><h4>Login</h4></a>
            <a class="nav-item nav-link" routerLink="/registration"><h4>Register</h4></a>
            <a class="nav-item nav-link" routerLink="/about"><h4>About</h4></a>
            <a class="nav-item nav-link" routerLink="/dashboard"><h4>Dashboard</h4></a>

 </div>

 So, How can i hide Login, Registration option once logged in successfully

Upvotes: 0

Views: 892

Answers (1)

saidutt
saidutt

Reputation: 289

There are numerous ways to it. It depends on your login mechanism. Let' say user has logged in and you are storing some credentials of the user (JWT token or some other property). Usually its stored in your localstorage for easy referral purposes.

So, the answer is basically -> user *ngIf on all the navigation links.

In html.

<a *ngIf="!loggedIn()" class="nav-item nav-link" routerLink="/login"><h4>Login</h4></a>
<a *ngIf="!loggedIn()" class="nav-item nav-link" routerLink="/registration">Register</h4></a>

In your .ts file.

loggedIn() {
           return localStorgae.getItem("some credential you stored while user logged In") ? true : false;
}

Also if you are using something like the above solution, don't forget to remove the values from localstorage when user logged Out.

So, during login

login() {
  // all your authentication code.
  localStorage.setItem("loggedIn", "value");
}

// where ever you need to check login, You can use localStorage.getItem("loggedIn");

Upvotes: 1

Related Questions