[Fixed] Async pipe subscription not work correctly when nested inside ngIf

Issue

I have a quick search box which I would like to have a loading animation. I used ng-template with ngIf to show/hide this animation. And I have some li’s nested inside the same div which subscribed to a search result Observable using async pipe to display results. This async pipe works great when there’s no *ngIf on the parent div, but seems it is not subscribing anymore when I apply ngIf. Is this an expected behavior? Or am I doing anything wrong?

My markup looks like this.

<input #searchBox type="text" (keyup)="itemLoading=true;searchTerm$.next(searchBox.value)"/>
<div *ngIf="!itemLoading else loading">
<!--Remove ngIf then items will display correctly when search-->
<!-- <div> -->
  <ul>
    <li *ngFor="let item of result$ | async ">{{item}}</li>
  </ul>
</div>
<ng-template #loading>
  <p>LOADING...</p>
</ng-template>

And I am using switchMap to run the search:

private source = of(['apple', 'pear', 'banana']).pipe(delay(500));

  searchTerm$ = new Subject<string>();
  result$: Observable<string[]>;
  itemLoading = false;  

  constructor() {
    this.result$ = this.searchTerm$.pipe(
      tap(term => console.log('search term captured: ' + term)),
      debounceTime(300),
      distinctUntilChanged(),
      switchMap(() => this.source.pipe(
        tap(_ => {
            console.log('source reached');
            this.itemLoading = false;
          })
      ))
    );
  }

When ngIf is present in parent div, the ‘source reached’ message is never logged in console, as well as the loading template keeps hanging there.

Here is a full working example of what I am talking about: https://stackblitz.com/edit/angular-2ukcqu

Solution

Rewriting the *ngIf as hidden should solve the problem. The reason result$ isn’t working is because those elements inside the *ngIf won’t be added to the dom until itemLoading is false. At that point they’ll subscribe to result$, but the event will have already occurred.

Alternatively shareReplay(1) might also do the trick without you having to rewrite anything else, as the reply will run when the Observable is subscribed too.

Solution A

<div [hidden]="itemLoading">
<!-- ... -->
</div>
<div [hidden]="!itemLoading">
  <p>LOADING...</p>
</div>

Solution B

this.result$ = this.searchTerm$.pipe(
  //...
  shareReplay(1)
);

Leave a Reply

(*) Required, Your email will not be published