Angular 2英雄之旅:按名称过滤英雄

时间:2016-12-22 12:11:30

标签: angular web typescript

我已经关注了Angular 2英雄之旅教程,目前我处于这个阶段:

https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

我可以在搜索栏中搜索,并出现英雄名称建议列表

Plunker:https://angular.io/resources/live-examples/toh-6/ts/eplnkr.html

然而,我想要的是一个过滤条,我搜索,并根据过滤条中的内容自动过滤英雄块。

例如,在我提供的链接中,如果我输入" Bo"在搜索栏中,我只想要英雄块" Bombasto"显示在屏幕上。当我清除搜索栏时,所有块都应该重新出现。有人知道怎么做吗?

1 个答案:

答案 0 :(得分:3)

看看我修改过的plunker:https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?p=preview

  1. 在dashboard.component.ts
  2. 中添加了Pipe
    @Pipe({
      name: 'filterHeros'
    })
    export class FilterHeroPipe {
      public transform(heros: Hero[], filter: string) {
        if (!heros || !heros.length) return [];
        if (!filter) return heros;
        return heros.filter(h => h.name.toLowerCase().indexOf(filter.toLowerCase()) >= 0);
      }
    }
    
    1. 在该dashboard.template
    2. 中使用此Pipe
      <h3>Top Heroes</h3>
      <div class="grid grid-pad">
        <a *ngFor="let hero of (heroes | filterHeros : heroSearch.curSearch )"  [routerLink]="['/detail', hero.id]"  class="col-1-4">
          <div class="module hero">
            <h4>{{hero.name}}</h4>
          </div>
        </a>
      </div>
      <br />
      <hero-search #heroSearch></hero-search>
      
      1. 更改HeroSearch组件:
      2.   private searchTerms = new Subject<string>();
          public curSearch: string; // !! NEW !!
        
          constructor(
            private heroSearchService: HeroSearchService,
            private router: Router) {}
        
          // Push a search term into the observable stream.
          search(term: string): void {
            this.curSearch = term;  // !! NEW !!
            this.searchTerms.next(term);
          }
        
        1. 不要忘记将我们的Pipe添加到我们的app.module:
        2. import { DashboardComponent, FilterHeroPipe }   from './dashboard.component';
          import { HeroesComponent }      from './heroes.component';
          import { HeroDetailComponent }  from './hero-detail.component';
          import { HeroService }          from './hero.service';
          import { HeroSearchComponent }  from './hero-search.component';
          
          @NgModule({
            imports: [
              BrowserModule,
              FormsModule,
              HttpModule,
              InMemoryWebApiModule.forRoot(InMemoryDataService),
              AppRoutingModule
            ],
            declarations: [
              AppComponent,
              DashboardComponent,
              HeroDetailComponent,
              HeroesComponent,
              HeroSearchComponent,
              FilterHeroPipe
            ],
            providers: [ HeroService ],
            bootstrap: [ AppComponent ]
          })
          export class AppModule { }