Reputation: 42
I've implemented a bootstrap navbar in my Angular app with a couple of links. I want to hide the login
and register
links if the user is logged in, and show the profile
link. If the user is not logged in, show login
and register
, hide profile
.
...
<li class="nav-item" *ngIf="user">
<a class="nav-link" href="profile" id="profile" >Profile</a>
</li>
<li class="nav-item" *ngIf="!user">
<a class="nav-link" href="login"><button class="btn btn-sm" >Login</button></a>
</li>
<li class="nav-item" *ngIf="!iuser">
<a class="nav-link" href="register"><button class="btn btn-sm" >Register</button></a>
</li>
...
I'm using firebase for authentication and checking if the user is logged in like this:
checkUser() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('logged in', user);
} else {
console.log('not logged in');
}
});
}
The function works just fine but it seems the *ngIf
in the navbar doesn't pick up the user
from the function.
Upvotes: 0
Views: 3860
Reputation: 42
A better way to reference nav links is to use routerLink.
...
<li class="nav-item">
<a class="nav-link" routerLink="/profile" routerLinkActive="active"
*ngIf="user">Profile</a>
</li>
...
Define a user variable in your class and set its value in the callback: public user: string;
...
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.user = user;
console.log('logged in', user);
} else {
console.log('not logged in');
}
});
Thanks to ConnorsFan for the insight.
Upvotes: 0
Reputation: 1547
You can create new subject and emit a value and use in ngIf with the help of async pipe should work. Please try as follows,
...
isUserLoggerdIn$ = new Subject<any>();
checkUser() {
firebase.auth().onAuthStateChanges((user) => {
if(user) {
this.isUserLoggedIn$.next(true);
} else {
this.isUserLoggedIn$.next(false);
}
});
}
...
Then in your template you can achieve as follows
...
<li class="nav-item" *ngIf="isUserLoggerdIn$ | async">
<a class="nav-link" href="profile" id="profile" >Profile</a>
</li>
...
Upvotes: 3