条件可能会影响
@if
的内容投影,因此我们可以在可观察的级别进行过滤。
您可以使用
mat-option
首先,我们创建一个可观察的名为
rxjs
,其中包含基于搜索值并搜索产品过滤的条件。
我们从
filteredOptions$
开始,然后对其进行管道,我们使用products$
与形式控制值更改结合,然后应用三元条件以仅在存在搜索值时返回过滤的数据。
combineLatestWith
Full代码:
TS:
filteredOptions$: Observable<any[]> = this.products$.pipe(
combineLatestWith(this.search.valueChanges),
map(([products, value]: any) => {
console.log(products, value);
const filterValue = value?.toLowerCase();
return filterValue
? products.filter((product: any) =>
product.productCode?.toLowerCase()?.includes(filterValue)
)
: [];
})
);
Html:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map, startWith, combineLatestWith } from 'rxjs/operators';
import { AsyncPipe, JsonPipe } from '@angular/common';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
/**
* @title Filter autocomplete
*/
@Component({
selector: 'autocomplete-filter-example',
templateUrl: 'autocomplete-filter-example.html',
styleUrl: 'autocomplete-filter-example.css',
imports: [
FormsModule,
MatFormFieldModule,
MatInputModule,
MatAutocompleteModule,
ReactiveFormsModule,
AsyncPipe,
JsonPipe,
],
})
export class AutocompleteFilterExample {
search = new FormControl('');
products$: Observable<Array<any>> = of([
{ productCode: 'one', brand: 'one', name: 'one' },
{ productCode: 'two', brand: 'two', name: 'two' },
{ productCode: 'three', brand: 'three', name: 'three' },
]);
filteredOptions$: Observable<any[]> = this.products$.pipe(
combineLatestWith(this.search.valueChanges),
map(([products, value]: any) => {
console.log(products, value);
const filterValue = value?.toLowerCase();
return filterValue
? products.filter((product: any) =>
product.productCode?.toLowerCase()?.includes(filterValue)
)
: [];
});
);
onSelect(e: any) {}
resetProducts() {}
}
stackblitzdemo