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

Angular 14中如何在mat-autocomplete面板打开时聚焦选中的mat-option

解决Angular 14 mat-autocomplete选中项焦点问题

要实现下拉面板打开时自动聚焦到已选中的选项,可通过以下步骤修改代码:

1. 模板修改

给mat-autocomplete绑定opened事件,用于触发焦点设置逻辑:

<mat-form-field>
  <input
    matInput
    type="text"
    [formControl]="formControl"
    [matAutocomplete]="autoComplete"
    [value]="value"
    (blur)="resetInput(value)"
    (focus)="emptyInput()"
  >

  <mat-autocomplete
    #autoComplete="matAutocomplete"
    [displayWith]="displayWithFn"
    (optionSelected)="doSomething($event)"
    (opened)="onAutocompleteOpened()"
  >
    <mat-option
      *ngFor="let oneOption of options$ | async"
      [value]="oneOption"
    >
      {{ oneOption.title }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

2. 组件逻辑实现

在组件中获取所有mat-option的引用,在面板打开时定位到已选中的选项并设置焦点:

import { Component, ViewChildren, QueryList } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatOption } from '@angular/material/autocomplete';
import { Observable } from 'rxjs';

// 替换为你的选项类型定义
interface YourOptionType {
  id: number;
  title: string;
}

@Component({
  selector: 'your-component-selector',
  templateUrl: './your-component.component.html'
})
export class YourComponent {
  formControl = new FormControl();
  options$!: Observable<YourOptionType[]>;
  value!: YourOptionType;

  // 获取所有mat-option实例
  @ViewChildren(MatOption) matOptions!: QueryList<MatOption>;

  onAutocompleteOpened() {
    // 等待异步选项渲染完成
    setTimeout(() => {
      const selectedValue = this.formControl.value;
      if (!selectedValue) return;

      // 匹配对应的选项(用id等唯一标识比较,避免对象引用差异问题)
      const targetOption = this.matOptions.find(option => 
        option.value.id === selectedValue.id
      );

      if (targetOption) {
        // 设置焦点到选中项
        targetOption.focus();
        // 可选:滚动到可视区域,避免选项在视图外
        targetOption._elementRef.nativeElement.scrollIntoView({ block: 'nearest' });
      }
    });
  }

  // 原有方法保持不变
  resetInput(value: YourOptionType) {
    // 实现你的重置逻辑
  }

  emptyInput() {
    // 实现你的清空输入逻辑
  }

  doSomething(event: any) {
    // 实现选项选中后的逻辑
  }

  displayWithFn(option: YourOptionType): string {
    return option ? option.title : '';
  }
}

关键说明

  • @ViewChildren(MatOption)用于获取所有下拉选项的实例,方便后续查找匹配项。
  • 用setTimeout等待异步选项渲染完成,确保能找到对应的DOM元素。
  • 选项匹配逻辑:如果选项是对象,不要直接用===比较引用,建议用id等唯一字段判断,避免因对象引用不同导致匹配失败。
  • targetOption.focus()直接设置焦点到目标选项,scrollIntoView可选,用于确保选项在可视区域内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:40:22