[英]How to get same name once in the filter dropdown using angular2/typescript
I have a filter drop down in table1 which is present via table2 entries. 我在table1中有一个过滤器下拉列表,该过滤器通过table2条目存在。 In table2 if i have "Car" 2 times, den in filter dropdown also its showing 2 times Car, Car.
在表2中,如果我有2次“汽车”,则过滤器下拉列表中的den也将显示2次汽车,汽车。 How do i make it to come only once.
我如何使它只出现一次。 Please help
请帮忙
HTML Code: HTML代码:
<div class="queryBox col-lg-2 col-md-2 col-sm-2 col-xs-3 taskDiv">
<label>Vehice</label>
<ng-select [options]="Vehice" [(ngModel)]="filter.vehice" class='filterDropDown' placeholder="All" [allowClear]="true">
</ng-select>
</div>
Ts Code: 电话代码:
this.ApiService
.getVehice ()
.subscribe(
vehicle => {
this.Vehice = vehice.map(function(item) {
if(item.vehicle ) {
return {"value":item.vehice,"label":item.vehice};
}
})
I am not sure I would use a Pipe for filtering unique results. 我不确定我会使用管道过滤唯一结果。 I would probably just do something like this:
我可能会做这样的事情:
let elements = [{'name' : 'Apple', 'type' : 1},
{'name' : 'Apple', 'type' : 1},
{'name' : 'Pear', 'type' : 4}];
function filterUniqueResults(list: any[]): any[]{
let uniqueList = [];
elements.forEach(element => {
if(uniqueList.indexOf(element) === -1){
uniqueList.push(element);
}
});
return uniqueList;
}
let result = filterUniqueResults(elements);
Isn't it just this what you asked for? 这不仅仅是您要的吗?
From the code you posted it seems like you asked for something else instead, which is "how do I filter certain values given an attribute?" 从您发布的代码中,您似乎需要其他内容,这就是“如何过滤给定属性的某些值?” which you can do with a Pipe like this:
您可以使用这样的Pipe来做到这一点:
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
name: 'exclude'
})
@Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any[], field: string, value: string): any[] {
if (!items) return [];
return items.filter(it => it[field] != value);
}
}
and then 接着
<li *ngFor="let item of items | exclude : 'type' : 4">{{item.name}}</li>
or 要么
<li *ngFor="let item of items | exclude : 'name' : 'apple'">{{item.name}}</li>
EDIT So to answer you comment: 编辑因此,为了回答您的评论:
this.apiService.getVehicles().subscribe(
result => this.vehicles = filterUniqueResults(result));
given your apiService looks like this: 鉴于您的apiService看起来像这样:
public getVehicles(): Observable<Vehicle[]> {
return this.http.get("http://whatever")
.map(res => res.json().data || {})
.catch(error => console.error(error));
}
var valArray: any = [];
function functionName(id){
var idx = this.valArray.indexOf(id);
if (idx > -1) {
this.valArray.splice(idx, 1);
}
else {
this.valArray.push(id);
}
}
In valArray array you will get the unique records.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.