技术笔记Web前端之路让前端飞

Angular2入坑记(四)官方文档之搜索问题

2017-10-26  本文已影响271人  HalShaw
Angular

前言

1.代码

<div id="search-component">
  <h4>Hero Search</h4>
  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
  <div>
    <div *ngFor="let hero of heroes | async"
         (click)="gotoDetail(hero)" class="search-result" >
      {{hero.name}}
    </div>
  </div>
</div>
  search(term: string): void {
    this.searchTerms.next(term);
  }
 
  ngOnInit(): void {
    this.heroes = this.searchTerms
      .debounceTime(300)        // wait 300ms after each keystroke before considering the term
      .distinctUntilChanged()   // ignore if next search term is same as previous
      .switchMap(term => term   // switch to new observable each time the term changes
        // return the http search observable
        ? this.heroSearchService.search(term)
        // or the observable of empty heroes if there was no search term
        : Observable.of<Hero[]>([]))
      .catch(error => {
        // TODO: add real error handling
        console.log(error);
        return Observable.of<Hero[]>([]);
      });
  }

2.问题

3.解决方案

// HTML

<input [(ngModel)]="searchBox" id="search-box" (keyup)="search(event)"/>
// Compoenet

searchBox: string // declare before constructor into your component

// declare after constructor into your component

@HostListener('document:keyup', ['$event'])
    search(event: KeyboardEvent): void {
      this.searchTerms.next(this.searchBox);
    }

4.最终解决方案:

总结

上一篇 下一篇

猜你喜欢

热点阅读