angulartypescriptangular-ng-ifbehaviorsubject

*ngIf with a NOT (!) with async pipe for BehaviorSubject or Promise throws condition error


*ngIf for async NOT condition?

So I have a fairly simple login service that uses the behavior subject library to know when a user is logged in.

login.service.ts:

constructor(private http: HttpClient){
    this.loggedSubject = new BehaviorSubject<boolean>(false);
}

getLoginStatus(){
    return this.loggedSubject.asObservable();
}

And a login component, in which I want to make the register button NOT show if the user is logged in.

So I did followings in login.component.html:

<button mat-button class="menu-button" routerLink="/register"  (click)="sidenav.toggle()" *ngIf="!getLoginStatus() | async">
      <mat-icon>key</mat-icon>
      <span>Register</span>

where I've got:

ERROR

src/app/header/header.component.html:33:102 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(obj: Observable<unknown> | Subscribable<unknown> | Promise<unknown>): unknown', gave the following error.
    Argument of type 'boolean' is not assignable to parameter of type 'Observable<unknown> | Subscribable<unknown> | Promise<unknown>'.
  Overload 2 of 3, '(obj: null | undefined): null', gave the following error.
    Argument of type 'false' is not assignable to parameter of type 'null | undefined'.
  Overload 3 of 3, '(obj: Observable<unknown> | Subscribable<unknown> | Promise<unknown> | null | undefined): unknown', gave the following error.
    Argument of type 'false' is not assignable to parameter of type 'Observable<unknown> | Subscribable<unknown> | Promise<unknown> | null | undefined'.

33     <button mat-button class="menu-button" routerLink="/register"  (click)="sidenav.toggle()" *ngIf="!getLoginStatus() | async">
                                                                                                        ~~~~~~~~~~~~~~~~~

  src/app/header/header.component.ts:21:16
    21   templateUrl: './header.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component HeaderComponent.

The above works perfectly without the "!" (not) operator. Also from what I've seen there's not ngNotIf, how can I bypass this problem?

Thanks to everyone for any answer.


Solution

  • *ngIf="!(getLoginStatus() | async)"
    

    Demo https://stackblitz.com/edit/angular-kwl3qt?file=src/main.ts