У меня есть этот фрагмент , который фильтрует список после дополнительных полей.
Если я проверю john
и mike
, это приведет к:
0 - Джон, g1
1 - Майк, g2
Но если я проверю john
, mike
и g3
(что не относится ни к одному из этих 2пользователи), из-за канала, он будет искать 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
<code><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 }}
{{user.id}} - {{user.name}}, {{user.group}}
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);
});
}
}