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

Angular搜索无匹配结果时如何隐藏对应组件

解决方案

步骤1:修改TypeScript逻辑,新增匹配状态判断

首先在组件类中新增3个显隐控制变量,同时补全三个模块的匹配校验逻辑:

// 组件类新增变量
filterValue = ''; // 确保默认值为空字符串
hasMatchingAttachments = true;
hasMatchingGroups = true;
hasMatchingTraining = true;
// 原始数据备份变量(可选,避免每次搜索都重复请求接口)
originalEntity: any;

// 修改loadApplication方法中的subscribe回调逻辑
.subscribe((entity) => {
  // 首次请求时备份原始数据,不需要重复请求可以去掉接口调用直接用备份数据过滤
  if (!this.originalEntity) this.originalEntity = JSON.parse(JSON.stringify(entity));
  this.entity = entity;
  this.ancestor = this.entity.channels.get(0);

  // 1. 处理附件过滤与显隐判断
  if (this.filterValue) {
    this.entity.attachments = this.entity.attachments.filter((app) => {
      return app.name.toLowerCase().includes(this.filterValue.toLowerCase());
    });
  } else {
    // 搜索词为空时恢复原始附件数据
    this.entity.attachments = this.originalEntity.attachments;
  }
  this.hasMatchingAttachments = !this.filterValue || this.entity.attachments.length > 0;

  // 2. 处理应用组过滤与显隐判断,匹配字段可根据实际业务调整
  let filteredGroups: any[] = [];
  if (this.filterValue) {
    filteredGroups = this.entity.entityGroups.filter(group => {
      // 示例匹配组名称,如需匹配组内应用内容可自行扩展逻辑
      return group.name.toLowerCase().includes(this.filterValue.toLowerCase());
    });
  } else {
    filteredGroups = this.originalEntity.entityGroups;
  }
  this.entity.entityGroups = filteredGroups;
  this.hasMatchingGroups = !this.filterValue || filteredGroups.length > 0;
  this.entityGroup = filteredGroups.filter(
    (r) => r.entityType === EntityType.Application,
  );

  // 3. 处理培训模块显隐判断,匹配规则根据app-training实际展示内容调整
  let trainingMatch = true;
  if (this.filterValue) {
    // 示例:判断培训模块的标题、内容等字段是否存在匹配,按需修改
    trainingMatch = this.entity.trainingContents?.some(item => 
      item.title.toLowerCase().includes(this.filterValue.toLowerCase())
      || item.desc.toLowerCase().includes(this.filterValue.toLowerCase())
    ) ?? false;
  }
  this.hasMatchingTraining = !this.filterValue || trainingMatch;
});

步骤2:修改HTML模板,新增显隐控制

给每个组件的外层容器增加*ngIf判断,无匹配结果时直接隐藏容器:

<!-- attachments -->
<div *ngIf="hasMatchingAttachments">
  <app-attachment [attachments]="entity.attachments"></app-attachment>
</div>
<!-- appgroups -->
<ng-container *ngIf="hasMatchingGroups">
  <div *ngFor="let entityGroup of entity.entityGroups">
    <app-application-group [entityGroup]="entityGroup" [entity]="entity"></app-application-group>
  </div>
</ng-container>

<!-- Training and Support -->
<div *ngIf="hasMatchingTraining">
  <app-training [entity]="entity"></app-training>
</div>

可选优化建议

  • 若不想在父组件耦合app-training的内部逻辑,可以给app-training组件新增一个hasMatch的Output事件,组件内部过滤完成后将是否有匹配结果的状态抛给父组件,父组件接收后更新hasMatchingTraining的值即可,逻辑更解耦。
  • 可以把通用的字符串匹配逻辑抽成公共工具方法,减少重复代码。
  • 如果你不需要每次搜索都重新请求接口,可以直接用首次请求备份的originalEntity做本地过滤,减少服务端压力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:15:02