以编程方式删除选择上的焦点/模糊(Angular6 材质)

Aes*_*eir 6 angular

我复制了 Angular 6 Material autocomplete 简单示例: Simple Autocomplete

我试图弄清楚一旦做出选择,如何移除焦点。

我添加了以下更改:

在 HTML 中

<mat-autocomplete #autoGroup="matAutocomplete" (optionSelected)="onSelectionChanged($event)">
Run Code Online (Sandbox Code Playgroud)

在组件中

  onSelectionChanged(event: MatAutocompleteSelectedEvent) {
    console.log(event.option.value);
  }
Run Code Online (Sandbox Code Playgroud)

在将值输出到控制台后,我想从输入字段中移除焦点,但不确定如何执行此操作。

Fat*_*zli 6

mat-focused级垫形场导致把重点放在垫自动完成,通过从毡状场移除它,它就会不集中,

在组件中

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

在 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>
Run Code Online (Sandbox Code Playgroud)

检查此堆栈闪电战

根据 Aeseir 的发现建立在答案的基础上

将 @ViewChild 链接到您的输入。

export class WhateverComponent {
@ViewChild('textInput') textInput: ElementRef;
//all other code
}
Run Code Online (Sandbox Code Playgroud)

在 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();        
  }
Run Code Online (Sandbox Code Playgroud)

以上将把选定的值记录到控制台,模糊焦点并重置表单(如果你使用表单并想要这个功能)。

  • 什么是“this.matInputMain”?它从哪里来的? (3认同)