Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only show div when observable stream is empty

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>
like image 713
Syntactic Fructose Avatar asked Oct 18 '25 18:10

Syntactic Fructose


1 Answers

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>
like image 195
undefined Avatar answered Oct 20 '25 08:10

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!