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

Angular实现搜索列表无匹配时显示「创建值」组件方案咨询

实现搜索无匹配时显示「创建值」组件的方案

一、搜索值与列表值的比对逻辑

你已经在onSearch方法里实现了核心的比对过滤逻辑,针对不同字段类型做了适配:

onSearch(query: string): void {
    if (!this.isValuesMode) {
        this.search.emit(query);
    } else {
        if (query) {
            switch (this.selectedFieldType) {
            case 'Person':
                // 针对Person类型,拼接姓名后做大小写不敏感的包含匹配
                this.searchValues = this.values.filter(elem => {
                    const name = this.teamMap[elem.title].firstName + ' ' + this.teamMap[elem.title].lastName;
                    return name.toLowerCase().includes(query.toLowerCase());
                });
                break;
            case 'Dropdown':
            case 'Multiselect':
                // 针对下拉/多选类型,直接用title做大小写不敏感的包含匹配
                this.searchValues = this.values.filter(elem => elem.title.toLowerCase().includes(query.toLowerCase()));
                break;
            }
            this.cdRef.markForCheck();
        } else {
            // 空搜索时重置为完整列表
            this.searchValues = this.values;
            this.cdRef.markForCheck();
        }
    }
    this.searchQuery = query;
}

核心思路:

  • 统一转小写处理,避免大小写差异导致匹配失败
  • 用Array.filter()过滤出包含搜索关键词的列表项,结果存入searchValues
  • 空搜索时重置为原始列表,确保正常显示所有选项

二、控制「创建值」组件的显示

通过*ngIf设置判断条件,仅当无匹配项时显示组件,你的现有逻辑已经覆盖了需求:

.create-value(
    '*ngIf'='searchQuery && isValuesMode && ["Dropdown", "Multiselect"].includes(selectedFieldType) && !searchValues.length'
    '[ngClass]'='{"active":!searchValues.length}'
    '(click)'='onQuickCreateFieldValue($event)'
)
    .text CREATE VALUE
    info-item
        .custom-icon('[ngStyle]'="{'background-color': DEFAULT_COLOR}")
        info-item-text.in-dropdown('[text]'='searchQuery')

条件拆解:

  • searchQuery:确保用户输入了搜索内容(空搜索不显示组件)
  • isValuesMode:当前处于值选择模式
  • ["Dropdown", "Multiselect"].includes(selectedFieldType):仅对下拉/多选字段生效
  • !searchValues.length:过滤后的结果为空,即没有匹配到任何列表项

三、创建值的触发逻辑

点击「创建值」时,你已经实现了基于搜索关键词生成新值并向外触发事件的逻辑:

onQuickCreateFieldValue(event: MouseEvent): void {
    const newValue = {
        title: this.searchQuery,
        properties: [
            {
                name: 'sequence',
                value: this.selectedField.values.length.toString()
            },
            {
                name: 'color',
                value: this.DEFAULT_COLOR
            }
        ]
    };
    this.quickCreateFieldValue.emit({value: newValue, selectedField: this.selectedField, projectId: this.entity.projectId});
}

注意事项

  • 变更检测:调用cdRef.markForCheck()确保在OnPush变更检测策略下视图能及时更新
  • 大小写兼容:统一转小写的处理避免了用户输入大小写不同导致的匹配遗漏
  • 边界处理:空搜索时重置列表,避免误显示「创建值」组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:00:45