在我的代码中,我试图从列表中筛选元素,并在一次编写多个单词时尝试过滤该元素。现在,如果我按正确的顺序写出单词,我就可以过滤元素。例如,我可以在编写'red book love'元素时过滤'red book'元素,但在编写'red love'时也希望过滤它。这是我的代码,我应该做些什么来实现我想要的?
HTML:
<mat-form-field appearance="outline" fxFlex="100" class="w-100-p pr-8">
<mat-label>Product</mat-label>
<input type="text" required matInput [(ngModel)]="product" name="product"
(input)="onProductSearchChange($event.target.value)" [matAutocomplete]="autoProductId">
<button mat-button matSuffix mat-icon-button aria-label="Clear" (click)="product = null" type="button">
<mat-icon>block</mat-icon>
</button>
<mat-autocomplete autoActiveFirstOption #autoProductId="matAutocomplete"
[displayWith]="displayProduct.bind(this)" (optionSelected)="filterProduct($event.option.value)">
<mat-option *ngFor="let prm of productList" [value]="prm">
{{prm?.StockIntegrationCode +' '+ prm?.ProductName}}
</mat-option>
</mat-autocomplete>
</mat-form-field>TS:
onProductSearchChange(search: string) {
let filterValue = (search as any).toLocaleLowerCase("tr");
if (
this._adminService.products &&
this._adminService.products.length > 0
) {
this.productList = this._adminService.products.filter(
(x) =>
x.StockIntegrationCode.indexOf(filterValue) >= 0 ||
(x.ProductName as any)
.toLocaleLowerCase("tr")
.indexOf(filterValue) >= 0
);
}
if (!search) {
this.product = null;
this.productList = this._adminService.products;
}
}
displayProduct(product: IProduct): string | undefined {
return product
? product.StockIntegrationCode + " - " + product.ProductName
: "";
}发布于 2022-01-31 09:01:36
我不知道你是希望所有的单词匹配,还是只想匹配其中的一个单词,所以这两种解决方案都是这样的。我也不知道股票集成代码是什么,所以我假设它在代码或名称中都有匹配。
只有一个单词与匹配
onProductSearchChange(search: string) {
if (!search) {
this.product = null;
this.productList = this._adminService.products;
return; //Return because the string is empty
}
let filterValue = search.toLocaleLowerCase('tr');
let values = filterValue.split(' ');
if (this._adminService.products && this._adminService.products.length > 0) {
this.productList = this._adminService.products.filter((x) => {
for (const value of values) {
if (
x.StockIntegrationCode.includes(value) ||
x.ProductName.toLocaleLowerCase('tr').includes(value)
)
return true;
}
return false;
});
}
}所有单词匹配
onProductSearchChange(search: string) {
if (!search) {
this.product = null;
this.productList = this._adminService.products;
return; //Return because the string is empty
}
let filterValue = search.toLocaleLowerCase('tr');
let values = filterValue.split(' ');
if (this._adminService.products && this._adminService.products.length > 0) {
this.productList = this._adminService.products.filter((x) => {
for (const value of values) {
if (
!x.StockIntegrationCode.includes(value) &&
!x.ProductName.toLocaleLowerCase('tr').includes(value)
)
return false;
}
return true;
});
}
}我只是在空格上拆分了filterValue,然后逐字搜索。
https://stackoverflow.com/questions/70922686
复制相似问题