【发布时间】:2019-05-07 21:54:26
【问题描述】:
我有 2 类过滤器:group 和 name。我该如何修改这段代码,因为它们不是管道,它们是独立的,name 过滤器覆盖 group 过滤器,并且向后。
.ts
changeGroup(event) {
const group = event.target.value;
const index = this.groupValue.indexOf(group);
if (index > -1) {
this.groupValue.splice(index, 1);
} else {
this.groupValue.push(group);
}
this.transform(this.usersList, 'group', this.groupValue)
if (this.groupValue.length == 0) {
this.transform(this.usersList, '', this.groupValue)
}
}
changeUser(event) {
const user = event.target.value;
const index = this.userValue.indexOf(user);
if (index > -1) {
this.userValue.splice(index, 1);
} else {
this.userValue.push(user);
}
this.transform(this.usersList, 'name', this.userValue)
if (this.userValue.length == 0) {
this.transform(this.usersList, '', this.userValue)
}
}
transform(items: any[], field: string, value: string[]): any[] {
if (!items) {
return [];
}
if (!field || !value || value.length <= 0) {
return items
}
this.newArray = items.filter(singleItem => {
return (singleItem != null && singleItem[field] != null && singleItem[field] != undefined && value.indexOf(singleItem[field]) >= 0);
});
return this.newArray
}
.html
<ng-container *ngFor="let group of groups">
<label class="btn btn-filter" id="bttns">
<input type="checkbox" name="customersGroupFilter" autoComplete="off" [value]="group" (change)="changeGroup($event)">
{{ group }}
</label>
</ng-container>
<br>
<ng-container *ngFor="let user of users">
<label class="btn btn-filter" id="bttns">
<input type="checkbox" name="customersUserFilter" autoComplete="off" [value]="user" (change)="changeUser($event)">
{{ user }}
</label>
</ng-container>
<table>
<thead>
<tr>
<th>Name</th>
<th>Group</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of newArray">
<td>{{user.name}}</td>
<td>{{user.group}}</td>
</tr>
</tbody>
</table>
感谢您的宝贵时间!
【问题讨论】:
-
首先,您甚至没有将功能用作
pipe。其次,我没有看到它们压倒任何东西,它们都有效。 -
这就是我问的原因,我不知道如何让它们像管道一样工作。其次,它们确实会覆盖。如果您检查
tim然后a,a将立即覆盖tim,我期待[]结果,因为tim不属于组a。不能回答的不要无礼,谢谢。 -
@Tenzolinho 你为什么说管道?你有什么想法?如果您想知道如何创建管道,请查看文档:angular.io/guide/pipes#custom-pipes 您必须创建一个由
pipe装饰的类,实现PipeTransform并覆盖transform方法。但我不明白你为什么需要管道。 -
庆幸你没有像this kind of pipes are discouraged那样制作管道。在不阅读您的代码的情况下,我建议您保持这种方式(即在您的组件中),并且不要用它制作管道。
-
我以前有管道,但我读到它们不好,所以我更改并移动了组件内的
transform函数。我的问题是我做错了什么,如何修改此代码以作为管道工作。这甚至可能吗?
标签: javascript html angular filter angular6