确保输入框绑定了matAutocomplete指令,并检查matAutocomplete选项的命名是否正确。
确保提供了正确的数据源。
检查mat-form-field是否正确包含了mat-autocomplete。
确保app.module.ts中包含了MatAutocompleteModule。
检查提供的数据源是否为空或格式不正确。
以下是一个示例代码:
HTML:
{{ country }}
TS:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
@Component({
selector: 'autocomplete-example',
templateUrl: 'autocomplete-example.html',
styleUrls: ['autocomplete-example.css'],
})
export class AutocompleteExample {
countryCtrl = new FormControl();
countries: string[] = ['USA', 'Canada', 'Germany', 'Italy', 'France'];
filteredCountries: Observable;
constructor() {
this.filteredCountries = this.countryCtrl.valueChanges.pipe(
startWith(''),
map((value) => this.filter(value))
);
}
filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.countries.filter((country) =>
country.toLowerCase().includes(filterValue)
);
}
}