要实现Angular Material自动完成过滤对象与KeyValue管道,可以按照以下步骤进行:
npm install @angular/material @angular/cdk
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule
的imports
数组中:imports: [
// ...
MatAutocompleteModule,
FormsModule,
ReactiveFormsModule,
// ...
]
countries
的数组:countries = [
{ code: 'US', name: 'United States' },
{ code: 'CA', name: 'Canada' },
{ code: 'MX', name: 'Mexico' },
// ...
];
mat-autocomplete
指令和mat-option
元素来创建自动完成控件。使用ngModel
指令来绑定自动完成控件的值,并使用[displayWith]
属性来指定显示选项的方式。例如:
{{ country.name }}
KeyValuePipe
管道来过滤对象的属性。例如:import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
@Component({
// ...
})
export class AppComponent {
countries = [
{ code: 'US', name: 'United States' },
{ code: 'CA', name: 'Canada' },
{ code: 'MX', name: 'Mexico' },
// ...
];
countryControl = new FormControl();
filteredCountries: Observable;
constructor() {
this.filteredCountries = this.countryControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): any[] {
const filterValue = value.toLowerCase();
return this.countries.filter(country =>
country.name.toLowerCase().includes(filterValue) || country.code.toLowerCase().includes(filterValue)
);
}
}
KeyValuePipe
管道来显示所选对象的键值。在你的组件模板中,使用{{ selectedCountry | keyvalue }}
来显示所选对象的键值。例如:Selected Country: {{ selectedCountry | keyvalue }}
这样,你就完成了Angular Material自动完成过滤对象与KeyValue管道的实现。当用户输入时,自动完成控件将根据输入值过滤选项,并在选择选项后显示所选对象的键值。