[英]Filter in the drop down data -Angular 6
I want Angular app to filter data from the dropdown, list of products are associated with the product number.我希望 Angular 应用程序从下拉列表中过滤数据,产品列表与产品编号相关联。 Below is the JSON structure.下面是 JSON 结构。
component.ts组件.ts
productlistArray = [{
number: "1",
productlist: [
{ name: "product_1_0" },
{ name: "product_1_1" }
]
}, {
number: "2",
productlist: [
{ name: "product_2_0" },
{ name: "product_2_1" }
]
}];
onclickx() {
this.consoleMessages += "called this function";
}
I have an input box (to search by product).我有一个输入框(按产品搜索)。 when I type product number it must list only products under product number.当我输入产品编号时,它必须仅在产品编号下列出产品。
component.html组件.html
<td>
<div class="form-group">
<input type="text" class="form-control" placeholder="Search By Product No" style="width:300px" [(ngModel)]="searchTerm"/>
</div>
<div class="form-group">
<mat-select (selectionChange)="onclickx($event.value)">
<mat-option *ngFor="let product of productlistArray" [value]="product.number">
{{product.productlist}}
</mat-option>
</mat-select>
</div>
</td>
pipe.ts pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name:"ProductFilter",
pure:true
})
export class ProductFilter implements PipeTransform {
transform(data: any[], searchTerm: string): any[] {
return data.filter(productlistArray =>(productlistArray.number == searchTerm));
}
}
Initially, when there is no searchTerm
entered, it will be undefined
so the filter will not return any data
.最初,当没有输入searchTerm
时,它将是undefined
的,因此过滤器不会返回任何data
。 Add a condition to return all data
if there is no searchTerm
.如果没有searchTerm
,则添加返回所有data
的条件。 As mentioned by @AJT82 in the comments, this logic should also be placed in the component.正如@AJT82 在评论中提到的,这个逻辑也应该放在组件中。
filteredProducts: any; // You should ideally create an interface instead
searchTerm: string;
filter() {
this.filteredProducts = this.searchTerm ? this.productlistArray.filter(productlistArray => productlistArray.number == this.searchTerm) : this.productlistArray;
}
Note : For formControl
, use valueChanges
to achieve the same注意:对于formControl
,使用valueChanges
来实现相同的
Then call this function on change
of the input
然后在change
input
时调用此 function
<input type="text" class="form-control" [(ngModel)]="searchTerm" (change)="filter()" placeholder="Search By Product No" style="width: 300px;" />
And use filteredProducts
in your template并在您的模板中使用filteredProducts
<mat-form-field>
<mat-select placeholder="Product" (selectionChange)="onclickx($event.value)">
<mat-option *ngFor="let product of filteredProducts" [value]="product.number">
{{product.productlist}}
</mat-option>
</mat-select>
</mat-form-field>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.