在Angular Material中,可以使用MatAutocomplete
组件来实现自动完成功能,并通过验证选项列表中的选项。下面是一个包含代码示例的解决方法:
MatAutocomplete
组件和FormControl
来实现自动完成输入框:
{{ option }}
FormControl
来处理输入框的值,并使用filter
方法过滤选项列表:import { Component } 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 {
myControl = new FormControl();
options: string[] = ['选项1', '选项2', '选项3'];
filteredOptions: Observable;
constructor() {
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));
}
}
在上面的代码中,options
数组是选项列表,filteredOptions
是过滤后的选项列表。在_filter
方法中,使用filter
方法和includes
方法来过滤选项列表中与输入值匹配的选项。
这样,输入框中只会验证和显示选项列表中的选项。如果输入的值不在选项列表中,输入框将显示为无效状态。