beachCode
beachCode

Reputation: 3530

Angular 4 clear results from search

I'm using the code below to provide an async search ahead feature for my component. After a search is done, how can I clear the results from a method in my component? Setting searchResults to an empty array means that it’s no longer the array of search results, so the search no longer works. When a selection is made, I need to clear the results and allow the user to search again.

searchResults: Observable<any>;
this.searchResults = 
      this.form.controls['search'].valueChanges
        .debounceTime(200)
        .switchMap(query => this.search.searchPeople(query));

Here's the template code:

<md-input-container style="width:500px">
   <input mdInput formControlName="search" placeholder="Search Name" />
 </md-input-container>

      <div *ngFor="let person of searchResults | async">
        <p><button md-raised-button color="primary" 
          (click)="selectPerson(person)">
          Select</button> {{person.firstName}}</p>
        <p><img [src]="person.photo.url"/></p>
        <hr/>
       </div>

And the search method:

searchPeople(query){
    return this.http.get(`${BASE_URL}?q=${query}`)
      .map((res:Response) => res.json())
      .map(json => json.items);
  }

Upvotes: 1

Views: 1212

Answers (1)

martin
martin

Reputation: 96969

You can merge search results with a Subject that will clear the results:

clearSearch = new Subject();
searchResults: Observable<any>;

...

this.searchResults = this.form.controls['search'].valueChanges
    .debounceTime(200)
    .switchMap(query => this.search.searchPeople(query))
    .merge(this.clearSearch.mapTo([]));

Then to clear the results just call:

this.clearSearch.next();

Upvotes: 3

Related Questions