我复制了 Angular 6 Material 自动完成简单示例: Simple Autocomplete
我想弄清楚如何在做出选择后移除焦点。
我添加了以下更改:
在 HTML 中
<mat-autocomplete #autoGroup="matAutocomplete" (optionSelected)="onSelectionChanged($event)">
在组件中
onSelectionChanged(event: MatAutocompleteSelectedEvent) {
console.log(event.option.value);
}
将值输出到控制台后,我想从输入字段中移除焦点,但不确定如何执行此操作。
最佳答案
mat-form-field 的 mat-focused
类会引起对 mat-auto-complete 的关注,通过将其从 mat-form-field 中移除,它将不会被关注,
在组件中:
export class AutocompleteSimpleExample {
myControl: FormControl = new FormControl();
public matForm ;
constructor(){
}
ngOnInit(){
this.matForm = document.getElementById("matForm")
}
options = [
'One',
'Two',
'Three'
];
test(option){
console.log(option)
setTimeout(function(){
this.matForm.classList.remove('mat-focused' )}, 100);
}
}
在 html 中:
<form class="example-form">
<mat-form-field class="example-full-width test" #matForm id="matForm">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" #textInput>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="test($event.option)">
<mat-option *ngFor="let option of options" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
检查这个stackblitz .
根据 Aeseir 的发现建立答案
将@ViewChild 链接到您的输入。
export class WhateverComponent {
@ViewChild('textInput') textInput: ElementRef;
//all other code
}
在 onSelectionChanged 函数中
onSelectionChanged(event: MatAutocompleteSelectedEvent) {
console.log(event.option.value);
// blur will remove focus on the currently selected element
this.matInputMain.nativeElement.blur();
// if you using form you can wipe the input too
this.yourForm.reset();
}
上面的代码会将所选值记录到控制台,模糊焦点并重置表单(如果您使用表单并想要此功能)。
关于angular - 以编程方式删除选择上的焦点/模糊(Angular6 Material ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771298/