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