可以通过使用MatAutocompleteSelectedEvent来获取当前所选项的值,并将它作为输入框的初始值进行设置,以阻止值的更改。下面是代码示例:
{{option}}
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent implements OnInit {
myControl = new FormControl();
options: string[] = ['Angular', 'React', 'Vue'];
filteredOptions: Observable;
constructor() { }
ngOnInit(): void {
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));
}
onOptionSelected(event: MatAutocompleteSelectedEvent): void {
this.myControl.setValue(event.option.value, {emitEvent: false});
}
}
在这个示例中,选中一个选项时,它不会改变输入框的值,而是将该选项设置为输入框的初始值。值的更改会被阻止。