使用ngx-mat-select-search时无法输入搜索内容问题求助
问题原因及修复方案
1. 搜索组件嵌套层级错误
你将ngx-mat-select-search组件嵌套在了<mat-option>标签内,官方要求搜索组件需和下拉选项的<mat-option>平级,作为<mat-select>的直接子节点。当前写法会导致搜索框区域被识别为可选下拉项,点击输入时会触发选项选中逻辑,打断输入事件,导致无法正常输入内容。
2. FormControl绑定冲突
<mat-select>绑定的formControlName="client"是用来存储用户选中的客户数据的,而你给ngx-mat-select-search也绑定了同一个[formControl]="client",会导致输入的搜索内容直接覆盖选中值,输入内容无法被识别为搜索关键词。需要单独声明一个用于搜索功能的FormControl。
3. 搜索事件绑定错误
ngx-mat-select-search不需要绑定(change)事件,应该监听搜索专用FormControl的valueChanges事件来过滤下拉列表数据。
修正后代码
组件TS代码
import { FormControl } from '@angular/forms'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; // 组件类内 private destroy$ = new Subject<void>(); // 单独声明搜索专用FormControl clientSearchCtrl: FormControl = new FormControl(''); // 存储全量客户原始数据 clientsData: any[] = []; // 过滤后展示的下拉选项数据 filteredClientsData: any[] = []; ngOnInit() { // 此处替换为你的全量客户数据源赋值逻辑 this.clientsData = []; this.filteredClientsData = [...this.clientsData]; // 监听搜索框输入变化,过滤下拉选项 this.clientSearchCtrl.valueChanges .pipe(takeUntil(this.destroy$)) .subscribe(searchVal => { this.filterClientOptions(searchVal); }); } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } // 客户选项过滤逻辑 filterClientOptions(searchVal: string) { if (!this.clientsData) return; const keyword = searchVal?.toLowerCase().trim() || ''; this.filteredClientsData = this.clientsData.filter(item => item.code?.toLowerCase().includes(keyword) || item.name?.toLowerCase().includes(keyword) ); }
模板HTML代码
<div *ngIf="testForStack()" class="test-form-group mt-5"> <div class="row"> <div class="col-md-2"> <label for="test-form-clientId" class="test-form-lbl test-form-lbl--required"> {{'CLIENTE.RESPONSIBLE' | translate}} </label> </div> <div class="col-md-4 mt-1"> <mat-form-field class="test-form-field"> <mat-select id="test-form-origin" formControlName="client" required> <!-- 搜索组件和mat-option平级,不需要额外包裹mat-option --> <ngx-mat-select-search ngDefaultControl [formControl]="clientSearchCtrl" noEntriesFoundLabel="No results found" placeholderLabel="Search" attr.aria-label="{{'GERAL.RESPONSAVEL' | translate}}" > <mat-icon ngxMatSelectSearchClear>delete</mat-icon> </ngx-mat-select-search> <!-- 下拉选项 --> <mat-option *ngFor="let item of filteredClientsData" [value]="item">{{item.code}} - {{item.name}}</mat-option> </mat-select> </mat-form-field> </div> <div class="col-md-2"> <label for="test-form-clientName" class="test-form-lbl"> {{'CLIENTE.NOME_DO_CLIENTE' | translate}} </label> </div> <div class="col-md-4 mt-1"> <label id="test-form-clientName">{{clientName}}</label> </div> </div> </div>
内容的提问来源于stack exchange,提问作者Carolina Freitas
相关产品推荐
相关产品推荐

