我修改plunker請看:https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?p=preview
- 增加了
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 { }
也許你可以創建一個最小的重擊者? – mxii
Theres a plunker in the link I offers(towards the bottom)。 – Seeker
我真的應該把它添加到帖子中。這裏你去https://angular.io/resources/live-examples/toh-6/ts/eplnkr.html – Seeker