angular - 以编程方式删除选择上的焦点/模糊(Angular6 Material )

标签 angular

我复制了 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/

相关文章:

angular - iOS11 Cordova Angular 4 wrap breaking SecurityError : history. replaceState()

html - 整页 ionic 加载而不是小框

javascript - 根据 Typescript 中的值对所有 JSON 键进行分组

Angular 11 在 SSR @nguniversal/express-engine ReferenceError : globalThis is not defined 上运行

angularjs - 如何在 ngx-bootstrap Modal 中使用 angularjs 升级组件?

javascript - 如何从json数据中过滤子菜单并绑定(bind)到angular2中的html

angular - 在不共享同一父组件的子组件之间共享 Angular 2 服务

javascript - 如何使用响应式(Reactive)表单向表单添加新控件而不出现错误 : "ERROR InternalError: "too much recursion"?

binding - 路由器导出的 Angular 2 输出

angular - ./node_modules/rxjs/_esm5/operators/index.js 中的错误 Angular 6 ng build --prod of/Resolve