此问题的解决方法是在 mat-option 标签中添加一个关闭面板的事件,然后在 ts 文件中调用该事件。
HTML 代码:
{{option}}
TS 代码:
import { Component,ViewChild } from '@angular/core';
import { MatAutocomplete } from '@angular/material/autocomplete';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent {
@ViewChild(MatAutocomplete) matAutocomplete: MatAutocomplete;
options: string[] = ['Angular', 'React', 'Vue'];
selected(event){
console.log(event.option.value);
}
closePanel(auto: MatAutocomplete){
auto.closePanel();
}
}
在上面的代码示例中,我们在 mat-option 标签的外部添加了一个按钮来关闭面板。然后在 ts 文件中使用 MatAutocomplete 的 closePanel 方法,将该方法传递到了 closePanel 函数中,该函数使用 ViewChild 获取 MatAutocomplete 实例,最后调用了 closePanel 方法来关闭面板。