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

Angular中*ngFor循环内点击隐藏div的问题求助

解决Angular中*ngFor循环列表点击隐藏对应元素的问题

看来你现在遇到的核心问题是:用了一个全局的show变量控制所有卡片的显示/隐藏,导致点击操作会影响整个列表,而不是单独对应的那一项。咱们得给每个循环出来的company项单独维护显示状态才行,下面给你两种实用的解决方案:

方案一:给每个company对象附加显示状态属性

这种方式最直观,直接在数据对象里添加状态字段,不用额外维护独立数组:

1. 组件类(example.component.ts)修改

假设你的companies数据是从接口或本地获取的,在拿到数据后给每个项加上showCard属性,默认设为true(初始显示):

export class ExampleComponent implements OnInit {
  companies: any[] = []; // 建议换成你实际的接口类型,比如Company[]

  ngOnInit(): void {
    // 模拟数据获取流程,替换成你实际的请求逻辑
    this.fetchCompanies().then(data => {
      this.companies = data.map(comp => ({
        ...comp,
        showCard: true // 给每个公司添加显示状态标记
      }));
    });
  }

  // 切换指定公司的卡片显示状态
  toggleCardVisibility(company: any): void {
    company.showCard = !company.showCard;
  }

  // 模拟接口请求,实际项目中替换为真实API调用
  private fetchCompanies(): Promise<any[]> {
    return Promise.resolve([
      { name: 'Alpha公司', data: '2024-05-01' },
      { name: 'Beta科技', data: '2024-05-15' }
    ]);
  }
}

2. 模板(example.component.html)修改

把*ngIf的条件改成对应company的showCard,再给触发元素绑定点击事件:

<div class="allCompanies" [@listAnimation]="companies.length"> <!-- 注意你原来的lenght是拼写错误,要改成length -->
  <div class="company" *ngFor="let comp of companies; let i = index">
    <div *ngIf="comp.showCard" class="card">
      <div class="row">
        <div class="col-sm-8">
          <p><strong>Name: </strong>{{comp.name}}</p>
          <p><strong>Data: </strong>{{comp.data}}</p>
        </div>
        <div class="btnDiv">
          <!-- 可以绑定按钮点击,也可以直接绑定card容器本身 -->
          <button (click)="toggleCardVisibility(comp)">隐藏卡片</button>
        </div>
      </div>
    </div>
  </div>
</div>

方案二:单独维护显示状态数组

如果不想修改原有的company数据结构,可以用一个独立数组来记录每个项的显示状态:

1. 组件类修改

export class ExampleComponent implements OnInit {
  companies: any[] = [];
  showStates: boolean[] = []; // 专门存储每个项的显示状态

  ngOnInit(): void {
    this.fetchCompanies().then(data => {
      this.companies = data;
      // 初始化状态数组,所有项默认显示
      this.showStates = new Array(data.length).fill(true);
    });
  }

  toggleCardVisibility(index: number): void {
    this.showStates[index] = !this.showStates[index];
  }
}

2. 模板修改

<div class="allCompanies" [@listAnimation]="companies.length">
  <div class="company" *ngFor="let comp of companies; let i = index">
    <div *ngIf="showStates[i]" class="card">
      <div class="row">
        <div class="col-sm-8">
          <p><strong>Name: </strong>{{comp.name}}</p>
          <p><strong>Data: </strong>{{comp.data}}</p>
        </div>
        <div class="btnDiv">
          <button (click)="toggleCardVisibility(i)">隐藏卡片</button>
        </div>
      </div>
    </div>
  </div>
</div>

另外提醒下:你模板里的companies.lenght是拼写错误,要改成companies.length,否则列表动画可能无法正常触发哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:47:28