gpt4 book ai didi

Angular 2 英雄之旅 : Filter heroes by name

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:10 24 4
gpt4 key购买 nike

我已经学习了 Angular 2 英雄教程,目前处于这个阶段:

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

我可以在搜索栏中搜索,然后出现一个英雄名称建议列表

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

但是,我想要的是一个过滤栏,我可以在其中搜索,并且根据过滤栏中的内容自动过滤英雄 block 。

例如,在我提供的链接中,如果我在搜索栏中输入“Bo”,我只希望英雄方 block “Bombasto”出现在屏幕上。当我清除搜索栏时,所有 block 都应该重新出现。有人知道怎么做吗?

最佳答案

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

  1. 向 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);
}
}
  1. 在该 dashboard.template 中使用此 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 组件:
  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 中:
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 { }

关于Angular 2 英雄之旅 : Filter heroes by name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41282926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com