【发布时间】:2018-11-15 14:39:17
【问题描述】:
I have this snippet 在更多字段之后过滤列表。
如果我检查john 和mike 会得到:
0 - 约翰,g1
1 - 迈克,g2
但是如果我检查john、mike和g3(不属于这两个用户中的任何一个),由于管道,它会搜索g3但没有结果:
如果我检查g3 不是结果null,但仍保留当前过滤列表,我该如何修改代码?
感谢您的宝贵时间!
app.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
users = [
{ 'id': '0', 'name': 'john', 'group': 'g1' },
{ 'id': '1', 'name': 'mike', 'group': 'g2' },
{ 'id': '2', 'name': 'anne', 'group': 'g3' },
{ 'id': '3', 'name': 'dan', 'group': 'g1' },
{ 'id': '4', 'name': 'zoe', 'group': 'g2' },
]
groupValue: string[] = []
userValue: string[] = []
changeGroup(event) {
const group = event.target.value;
const index = this.groupValue.indexOf(group);
if (index < 0) {
this.groupValue.push(group);
} else {
this.groupValue.splice(index, 1);
}
const newGroupValue = [];
newGroupValue.push.apply(newGroupValue, this.groupValue);
this.groupValue = newGroupValue;
}
changeUser(event) {
const user = event.target.value;
const index = this.userValue.indexOf(user);
if (index < 0) {
this.userValue.push(user);
} else {
this.userValue.splice(index, 1);
}
const newUserValue = [];
newUserValue.push.apply(newUserValue, this.userValue);
this.userValue = newUserValue;
}
}
app.html
<ng-container *ngFor="let user of users; let i=index">
<label class="btn btn-filter" id="bttns">
<input type="checkbox" name="customersUserFilter" autoComplete="off" [value]="user.name" (change)="changeUser($event)">
{{ user.name }}
</label>
</ng-container>
<br>
<ng-container *ngFor="let user of users; let i=index">
<label class="btn btn-filter" id="bttns">
<input type="checkbox" name="customersGroupFilter" autoComplete="off" [value]="user.group" (change)="changeGroup($event)">
{{ user.group }}
</label>
</ng-container>
<pre>You select groups {{ userValue | json }} {{ groupValue | json }}</pre>
<div *ngFor="let user of users | filter2 : 'name' : userValue | filter2 : 'group' : groupValue">
{{ user.id }} - {{ user.name }}, {{ user.group }}
</div>
filter.pipe.ts
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
name: 'filter2'
})
@Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any[], field: string, value: string[]): any[] {
if (!items) {
return [];
}
if (!field || !value || value.length <= 0) {
return items;
}
return items.filter(singleItem => {
return (singleItem != null && singleItem[field] != null && singleItem[field] != undefined && value.indexOf(singleItem[field]) >= 0);
});
}
}
【问题讨论】:
-
请在问题中包含相关代码。
-
@ConnorsFan stackblitz 就够了。为什么不编写一个单独的管道来应用一组过滤器,然后使用逻辑 OR 来应用过滤器,而不是当前的隐式 AND?
-
@YoukouleleY - stackblitz 是一个很好的补充,但并没有消除在问题中包含相关代码的需要,以使其完整且对未来的读者有用。外部链接不被认为是可靠的; stackblitz 可以被删除或重新用于其他目的。
-
@YoukouleleY 你能给我一个堆栈闪电战吗?我尝试了像你说的那样,但它不起作用。如果我问的太多,我很抱歉,但从星期一开始我一直在努力完成这项工作,我没有想法。
-
@Tenzolinho,如果我们检查 john mike g2 应该得到什么预期结果
标签: javascript angular filter