You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Mat-Autocomplete:选择下拉选项后如何移除输入框焦点

解决Angular Material mat-autocomplete选择选项后输入框自动失焦的问题

可以通过监听mat-autocomplete的optionSelected事件,在选项被选中后主动调用输入框的blur()方法实现失焦,具体步骤如下:

  1. 模板层修改
    给输入框添加模板引用变量(比如#autoInput),并给mat-autocomplete绑定optionSelected事件:

    <input type="text" 
           #autoInput
           matInput 
           [formControl]="myControl" 
           [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onOptionSelected(autoInput)">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
    
  2. 组件层实现失焦逻辑
    在组件类中定义onOptionSelected方法,接收输入框元素并调用blur():

    import { Component } from '@angular/core';
    import { FormControl } from '@angular/forms';
    import { Observable } from 'rxjs';
    import { map, startWith } from 'rxjs/operators';
    
    @Component({
      selector: 'autocomplete-overview-example',
      templateUrl: 'autocomplete-overview-example.html',
      styleUrls: ['autocomplete-overview-example.css'],
    })
    export class AutocompleteOverviewExample {
      myControl = new FormControl('');
      options: string[] = ['One', 'Two', 'Three'];
      filteredOptions: Observable<string[]>;
    
      ngOnInit() {
        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(inputElement: HTMLInputElement) {
        // 调用blur方法让输入框失焦
        inputElement.blur();
      }
    }
    
  3. 添加失焦后的CSS样式
    可以利用:not(:focus)伪类给失焦状态的输入框设置样式,或者通过添加自定义类的方式实现:

    /* 直接通过伪类设置失焦样式 */
    input.mat-input-element:not(:focus) {
      background-color: #f5f5f5;
    }
    
    /* 或者通过自定义类:先在onOptionSelected中添加类 inputElement.classList.add('blurred'); */
    input.mat-input-element.blurred {
      background-color: #f5f5f5;
    }
    

设置完成后,从下拉列表选择任意选项时,输入框会自动失去焦点,光标不再闪烁,同时可应用你需要的自定义样式。

内容的提问来源于stack exchange,提问作者tech freak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:32:59