如何为<mat-select>添加可输入自定义选项并解决空格触发下拉关闭问题?
故障原因
修复方案
- 第一步:给输入框绑定
keydown事件,拦截空格键的向上冒泡行为,注意不要阻止输入框本身的空格输入逻辑 - 第二步:补充自定义选项输入完成后的赋值逻辑,实现失焦后自动将输入内容设为选中值
完整可运行代码示例
HTML 模板部分
<mat-select [(ngModel)]="selectedValue" placeholder="选择选项"> <mat-option *ngFor="let option of optionList" [value]="option"> {{ option }} </mat-option> <!-- 最后一项为自定义输入框 --> <mat-option disabled class="custom-input-option"> <input type="text" placeholder="Add your custom option" (keydown.space)="$event.stopPropagation()" (blur)="handleCustomInput($event)" #customInput > </mat-option> </mat-select>
注意:给承载输入框的
mat-option加disabled属性,可以避免点击输入框区域时触发mat-option的选中逻辑,不会误把空的option设为选中值。
TS 逻辑部分
import { Component } from '@angular/core'; @Component({ selector: 'app-select-demo', templateUrl: './select-demo.component.html', styleUrls: ['./select-demo.component.scss'] }) export class SelectDemoComponent { optionList = ['option 1', 'option 2']; selectedValue: string = ''; handleCustomInput(event: FocusEvent): void { const inputEl = event.target as HTMLInputElement; const inputValue = inputEl.value.trim(); if (inputValue) { // 可选:如果需要把自定义选项加入选项列表,打开下面两行注释 // if (!this.optionList.includes(inputValue)) { // this.optionList.push(inputValue); // } this.selectedValue = inputValue; inputEl.value = ''; // 输入完成后清空输入框 } } }
可选样式优化
可以添加以下样式让输入框和普通选项的视觉风格更统一:
.custom-input-option { padding: 0 !important; &:hover { background: transparent !important; } input { width: 100%; padding: 0.75rem 1rem; border: none; outline: none; background: transparent; } }
内容的提问来源于stack exchange,提问作者Sunstrike527
相关产品推荐
相关产品推荐

