angularangular-ng-if

*ngIf not working as expected with observable


So I have these 2 buttons:

<a class="router-link nav-item" routerLink="/login" *ngIf="!isLoggedIn$ | async">
  Login
</a>
<a class="router-link nav-item" (click)="onLogout()" *ngIf="isLoggedIn$ | async">
  Logout
</a>

And the logout button works perfectly, as soon as the user is logged in the button appears. But the login button never appears.

This is the code behind the isLoggedIn$:

isLoggedIn$: Observable<boolean>;

ngOnInit() {
  this.isLoggedIn$ = this.authService.isLoggedIn;
}

AuthService:

private loggedIn = new BehaviorSubject<boolean>(false);

get isLoggedIn() {
  return this.loggedIn.asObservable();
}

Hope this is enough information and the problem is clear, thanks in advance!


Solution

  • Put the async pipe in parenthesis.

    <a class="router-link nav-item" routerLink="/login" *ngIf="!(isLoggedIn$ | async)">
      Login
    </a>
    <a class="router-link nav-item" (click)="onLogout()" *ngIf="isLoggedIn$ | async">
      Logout
    </a>