I want to display a simple list with two buttons, where one button is shown if I am logged in and the other if I am not.
<div>
<li class="nav-item">
<button *ngIf="token === ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="login()">Log In</button>
<button *ngIf="token != ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="logout()">Log Out</button>
</li>
</div>
Although initially I tried using ngIf for conditional rendering, it does not update instantly upon login or logout. In addition, as the login functionality is in another component, I am unsure of how to trigger the change from there.
Below is the code for my component:
import { Component, ElementRef, ViewChild} from '@angular/core';
import { Router } from '@angular/router';
import { faHamburger } from '@fortawesome/free-solid-svg-icons';
import { UsersService } from './services/user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-app';
token = this.userService.getToken();
@ViewChild('clickLogout')clickLogout:ElementRef;
faHamburger = faHamburger;
constructor(public userService: UsersService, public router: Router) { }
logout(){
this.userService.logout();
this.router.navigateByUrl('/login');
}
login(){
this.router.navigateByUrl('/login');
}
}
Currently, the page needs to be reloaded each time to toggle between the two buttons. I require an instant update upon login or logout without needing to refresh the page.