2016-12-22 56 views
1

我都跟着角2遊覽英雄教程,我目前在這個階段:角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

也許你可以創建一個最小的重擊者? – mxii

+0

Theres a plunker in the link I offers(towards the bottom)。 – Seeker

+0

我真的應該把它添加到帖子中。這裏你去https://angular.io/resources/live-examples/toh-6/ts/eplnkr.html – Seeker

回答

2

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

  1. 增加了Pipe到dashboard.component.ts
@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); 
    } 
} 
  • 使用此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> 
    
  • 更改該HeroSearch組分:
  • 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); 
        } 
    
  • 不要忘記添加我們Pipe我們app.module:
  • 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 { } 
    
    +0

    非常感謝你!這正是我所期待的。 – Seeker

    相關問題