I am facing a challenge with implementing *ngIf to hide the login/logout option in the navbar based on the user's authentication status. When logged in, I want to hide the logout link. Here is my current setup.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from './user';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app works!';
loginstatus: boolean = false;
constructor(private _userService: UserService, private _router: Router){}
onLogout(){
this._userService.logout();
this._router.navigate(['/login']);
}
ngOnInit(){
this.onLogout();
}
}
app.component.html
<ul class="navigation">
<li *ngIf="!loginstatus"><a routerLink="/login" routerLinkActive="active">Login</a></li>
<li *ngIf="loginstatus"><a (click)="onLogout()">Logout</a></li>
</ul>
<router-outlet></router-outlet>
login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators} from '@angular/forms';
import { UserService } from '../user.service';
@Component({
selector: 'login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit{
user = {
username: '',
password: ''
}
loginForm: FormGroup;
constructor(private _userService: UserService, private _formBuilder: FormBuilder){}
ngOnInit(){
this.loginForm = this._formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
}
onLogin(){
this._userService.postUserLogin(this.user)
.subscribe(token => {
console.log(localStorage.getItem('currentUser'));
})
err => console.log(err);
}
}
In my code snippet, the variable loginstatus determines the user's authentication state for hiding the login option. Now, my question is, how can I update the value of loginstatus from the login component to control the visibility of the login option in the navbar?