通常是因为Mat Autocomplete没有正确连接到FormControl。可以尝试在FormControl和Mat Autocomplete之间添加[(ngModel)],或者使用[formControl]属性替换[matAutocomplete]属性。
示例代码如下:
HTML模板:
组件:
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs'; import { map, startWith } from 'rxjs/operators';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent implements OnInit {
myControl = new FormControl();
options: string[] = ['Option 1', 'Option 2', 'Option 3'];
filteredOptions: Observable
constructor() { }
ngOnInit() { this.filteredOptions = this.myControl.valueChanges .pipe( startWith(''), map(value => this._filter(value)) ); }
private _filter(value: string): string[] { const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
} }