5

i'm trying to display element with ngif on boolean like this :

<li *ngIf="!include == true">
    <span class="badge badge-pill badge-danger">
        <i [ngClass]="hearthClass"></i>
    </span>
</li>

my include var il initialized to false and switch state like this :

this.localStorageService.getCurrentUser().then((res) => {
      this.userProfile = res;
       if(this.song.likes.includes(this.userProfile._id)){
         this.include = true
       }
      this.classHeart();
    });

thank you everybody !

Alexis Lapeze
  • 69
  • 2
  • 10

4 Answers4

1

! operator works first, then ==, so when you set include to true, ngIf result is false.

Just write

<li *ngIf="include">
    <span class="badge badge-pill badge-danger">
        <i [ngClass]="hearthClass"></i>
    </span>
</li>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

No need to use ! before include. Code would be like this

  <li *ngIf="include else notInclude">
     <span class="badge badge-pill badge-danger">
       <i [ngClass]="hearthClass"></i>
     </span>
  </li>
  <ng-template #notInclude></ng-template>

ng-template would be used as else block

Hallah
  • 111
  • 4
1

So I had the same issue.

First I am going to show how it was and how I fixed it.

Before:

export class SomeComponent {
  isUniquePage = true;
}

Html

<div class="col-lg-3" *ngIf="!isUniquePage">
Something
</div>

For some reason this wasn't working as expected. The column was always being displayed.

To make it work I just did this:

export class SomeComponent {
  isUniquePage : boolean = true;
}

After that the column hid.

It's kind of weird because then I removed the type annotation and everything worked as expected (just as I had it from the start).

I don't know why it doesn't work as expected from the beginning.

Sanchitos
  • 8,423
  • 6
  • 52
  • 52
0

I would make your localStorageService return an observable. So I would take a reactive approach to your setup.

import { from, Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';


// define variable in your class as
// userProfile$: Observable<UserProfile>
this.userProfile$ = from(this.localStorageService
  .getCurrentUser())
  .pipe(tap() => this.classHeart()
);

// define variable in your class as
// include$: Observable<boolean>
this.include$: Observable<boolean> = this.userProfile$.pipe(
  map(user: User) => this.song.likes.includes(user._id)
);
<li *ngIf="include$ | async">
    <span class="badge badge-pill badge-danger">
        <i [ngClass]="hearthClass"></i>
    </span>
</li>

When we suffix a variable name with a $ it means that this variable is an Observable, this is a standard within the Angular community.