Tom*_*dge 6 javascript pipe filter typescript angular
我正在使用Angular进行构建,并使用了一个过滤器管道来过滤*ngFor循环中下拉菜单中的所选选项。然后,内容将进行相应过滤。我想将选择选项交换为按钮或药丸。因此,当单击按钮时,将进行过滤-该按钮将充当开/关开关,因此您可以过滤多个选项。
这是我的stackblitz例子- https://stackblitz.com/edit/timeline-angular-7-tyle1f
<div class="form-group row">
<div class="col-sm">
<select class="form-control" name="locationFilter" id="locationFilter" [(ngModel)]="filteredLocation">
<option value="All">All</option>
<option *ngFor="let entry of timeLine | filterUnique" value="{{entry.location}}">{{entry.location}}
</option>
</select>
</div>
//Button filters below
<div ngDefaultControl [(ngModel)]="filteredLocation" name="locationFilter" id="locationFilter">
<button class="btn btn-primary" type="button" *ngFor="let entry of timeLine | filterUnique">{{entry.location}}</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我不确定如何使按钮以与未进行过滤相同的方式工作。
如果您想过滤多个选项,则必须调整过滤管道以适应要过滤的字符串数组。
因此,在您的FilterPipe转换函数中更改如下:
transform(value: string[], filterStrings: string[], propName: string): any {
if (value.length === 0 || !filterStrings || filterStrings.length === 0) {
return undefined;
}
const resultArray = [];
for (const item of value) {
if (filterStrings.indexOf(item[propName]) >= 0) {
resultArray.push(item)
}
}
return resultArray;
}
Run Code Online (Sandbox Code Playgroud)
之后,您需要向该timeline.component.ts文件添加一些代码:
保存所有活动过滤器选项的数组:
filteredLocations: string[] = [];
Run Code Online (Sandbox Code Playgroud)
打开或关闭选项的函数:
toggle(location) {
let indexLocation = this.filteredLocations.indexOf(location);
if (indexLocation >= 0) {
this.filteredLocations = this.filteredLocations.filter((i) => i !== location);
} else {
this.filteredLocations.push(location);
}
}
Run Code Online (Sandbox Code Playgroud)
现在更改模板(timeline.component.html):
删除选择框。
将点击处理程序添加到您的按钮:
<button (click)="toggle(entry.location)" class="btn btn-primary" type="button" *ngFor="let entry of timeLine | filterUnique">{{entry.location}}</button>
Run Code Online (Sandbox Code Playgroud)
最后,过滤器应该接受新的过滤位置:(我刚刚将filteredLocation更改为filteredLocations)
*ngFor="let entry of timeLine | filter:filteredLocations:'location'"
Run Code Online (Sandbox Code Playgroud)