4

I'm using a text search feature similar to the angular2 heros tutorial, but am having trouble hiding a div when user is not searching. I have the following code in my component:

searchLocations: Observable<Location[]>;
private searchTerms = new Subject<string>();

// ...

ngOnInit(): void {
    // ...
    this.searchLocations = this.searchTerms
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap(term => term
            ? this.locationSearchService.search(term)
            : Observable.of<Location[]>([]))
        .catch(error => {
            console.error(error);
            return Observable.of<Location[]>([]);
        });
}

then within my html, I display the results of a user searching with

<div class="results">
    <div *ngFor="let loc of searchLocations | async" class="search-result">
        {{ loc.name }}, {{ loc.adminName1 }}, {{ loc.countryCode }}
    </div>
</div>

But with my current code, the results div is always present. How can I check when an observable stream is empty? I tried .count() and .length(), but both of these also return observables.... I assume I need to do something like:

<div class="results" *ngIf="???">
    <!-- ... -->
</div>
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
  • Possible due of http://stackoverflow.com/questions/38057537/how-to-check-length-of-the-an-observable-array – yurzui Dec 25 '16 at 16:21

1 Answers1

16

In your ngIf directive, you should also use the async pipe, because this is Observable:

  <div class="results" *ngIf="!(searchLocations | async)?.length">
        <div *ngFor="let loc of searchLocations | async" class="search-result">
            {{ loc.name }}, {{ loc.adminName1 }}, {{ loc.countryCode }}
        </div>
    </div>
undefined
  • 6,366
  • 12
  • 46
  • 90