【发布时间】:2018-11-24 00:21:25
【问题描述】:
我已添加到表单输入中,该输入将按年龄范围过滤用户。为此创建了管道。现在我正在尝试在工作示例中实现这一点,在该示例中,使用其他管道基于其他形式过滤结果。如何在此工作示例中使用年龄范围管道并使这两个管道一起工作?代码如下:
年龄段管道
transform(value: any, args?: any): any
{ if(!args) return value;
return value.filter( item => item.age > args[0] && item => item.age < args[1])
);
}
args[0] 是最小值,args[1] 是最大值。
工作搜索示例管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(items: any[], value: string, prop: string): any[] {
if (!items) return [];
if (!value) return items;
return items.filter(singleItem =>
singleItem[prop].toLowerCase().includes(value.toLowerCase())
);
}
}
工作示例的 TypeScript
form: FormGroup;
@Output() autoSearch: EventEmitter<string> = new EventEmitter<string>();
@Output() groupFilters: EventEmitter<any> = new EventEmitter<any>();
searchText: string = '';
constructor(private fb: FormBuilder,
private userService: UserService) {}
ngOnInit(): void {
this.buildForm();
}
buildForm(): void {
this.form = this.fb.group({
name: new FormControl(''),
prefix: new FormControl(''),
position: new FormControl(''),
gender: new FormControl(''),
agefrom: new FormControl(''),
ageto: new FormControl('')
});
}
search(filters: any): void {
Object.keys(filters).forEach(key => filters[key] === '' ? delete filters[key] : key);
this.groupFilters.emit(filters);
}
}
HTML
<form novalidate
[formGroup]="form">
<h3>Group Filter</h3>
<div class="row">
<div class="col-md-3">
<input type="text"
formControlName="name"
class="form-control"
placeholder="name"
#searchName
/>
</div>
<div class="col-md-3">
<input type="text"
formControlName="agefrom"
class="form-control"
placeholder="age from"
#searchName
/>
</div>
<div class="col-md-3">
<input type="text"
formControlName="nageto"
class="form-control"
placeholder="age to"
#searchName
/>
</div>
<div class="col-md-3 col-sm-3">
<select class="form-control"
formControlName="prefix">
<option value="">Prefix</option>
<option value="MR">MR</option>
<option value="MS">MS</option>
</select>
</div>
<div class="col-md-3 col-sm-3">
<select class="form-control"
formControlName="position">
<option value="">Position</option>
<option value="admin">admin</option>
<option value="student">student</option>
</select>
</div>
<div class="col-md-3 col-sm-3">
<select class="form-control"
formControlName="gender">
<option value="">Gender</option>
<option value="M">male</option>
<option value="F">female</option>
</select>
</div>
<div class="col-md-3 col-sm-3">
<button class="btn btn-primary"
(click)="search(form.value)">Search</button>
</div>
</div>
</form><br/>
您可以在此处查看完整的代码示例: https://stackblitz.com/edit/ng6-multiple-search-values-smz1cb-solved-jx6kgc?file=src%2Fapp%2Fuser%2Ffilter.pipe.ts
如何在代码中实现该年龄范围管道并使其成为此工作示例的一部分?
【问题讨论】:
-
您可以通过使用两个单独的过滤器来实现这一点,否则您需要使用通用过滤器。让我知道你想要达到的目标。喜欢复杂性与简单性。
-
我需要任何简单的方法来让这个年龄段的输入过滤器和其他过滤器一样好用。唯一的挑战是在上述工作示例中实现年龄范围输入过滤器并使其工作。