【发布时间】:2017-07-03 04:05:08
【问题描述】:
我正在寻找一种过滤解决方案,可以实时过滤一组重复的元素。我在答案here 中有一个基本的管道解决方案。
我发现<input [(ngModel)]='query'/> 只有在同一个组件中才有效。
但是 - 我需要让过滤器值来自另一个组件中预先填充的单选按钮。
这是我目前的代码。
filter.component
<div class="topic" *ngFor="let topic of topics">
{{topic.term}}
<input [(ngModel)]="query" type="radio" name="topicFilter" [value]="topic.term"/>
</div>
grid.component
<router-outlet></router-outlet> // this pulls in the filter.component
<input [(ngModel)]="query"> // this is a text input that works as wanted ( for showing what I'm wanting to achieve )
<grid-item *ngFor="let user of users | topicFilterPipe: 'topic':query">
<a [routerLink]="['user-story', user.uid]">
<h1>{{user.fname}}</h1>
</a>
{{user.topic}}
</grid-item>
filter.pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'topicFilterPipe'
})
export class TopicFilterPipePipe implements PipeTransform {
public transform(value: Array<any>, keys: string, term: string) {
console.log('pipe has run');
if (!term) return value;
return (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
}
}
基本上 - 尝试实现与文本输入相同的方法,但使用 filter.component 中的选定单选。但是我正在努力将选定的值传递到管道中,然后使用 ngModel 进行过滤。谢谢!
注意:我对 angular2 非常陌生 + 过滤器组件必须保留在单独的组件中
【问题讨论】:
-
如果您有多于几行数据,使用管道进行过滤通常不是一个好主意。请参阅:angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe 您可以改为在组件本身中进行过滤。
-
@DeborahK 我至少有 500 行数据。所以你可能是对的。我将如何处理 filter.component 中的过滤并将其传递给 grid.component
-
在下面的答案中查看我的回复。
-
正如其他人在回答中提到的那样,服务是管理多个组件之间的状态信息的好方法。这就是你实际在做的事情,改变应用程序的状态。该服务也可以扩展为从其他过滤器传递信息,但目的应该保持一致。例如一个管理用户体验偏好的服务,另一个管理用户看到的广告流。
标签: angular