我已经关注了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"显示在屏幕上。当我清除搜索栏时,所有块都应该重新出现。有人知道怎么做吗?
答案 0 :(得分:3)
看看我修改过的plunker:https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?p=preview
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);
}
}
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 { }