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

Angular 7中循环生成Div点击切换图表与表格的实现求助

嘿,刚接触Angular不用慌~你的问题核心是每个循环生成的Div需要独立的状态控制,现在的全局方法没法区分不同的项,我给你调整下代码就能解决:

问题分析

你当前的showChart()和showTable()是全局方法,点击时没法知道操作的是哪个Div,所以所有项会一起变化。我们需要给每个数组项绑定独立的状态,用来跟踪当前显示图表还是表格。

修改后的完整代码

app.component.ts

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit{
  public array = [{"id":1,"chart":"chart1","table":"table1"},{"id":2,"chart":"chart2","table":"table2"},{"id":3,"chart":"chart3","table":"table3"}];

  ngOnInit() {
    // 给每个项添加独立状态,初始设为true(显示图表)
    this.array.forEach(item => {
      item.isChartVisible = true;
    });
  }

  // 一个方法搞定切换,接收当前项作为参数
  toggleView(item: any) {
    item.isChartVisible = !item.isChartVisible;
  }
}

app.component.html

<div style="float:left;margin-right:10px;border:1px solid; height:200px;width:200px;" class="list" *ngFor="let x of array">
  <!-- 根据状态切换显示的链接 -->
  <div (click)="toggleView(x)" *ngIf="!x.isChartVisible">
    <strong>show chart</strong>
  </div>
  <div (click)="toggleView(x)" *ngIf="x.isChartVisible">
    <strong>show table</strong>
  </div>

  <!-- 根据状态切换显示图表或表格 -->
  <div *ngIf="x.isChartVisible">{{x.chart}}</div>
  <div *ngIf="!x.isChartVisible">{{x.table}}</div>
</div>

关键说明

  1. 独立状态绑定:在ngOnInit里给每个数组项添加isChartVisible属性,初始值为true,对应你要的初始状态(显示chart和“show table”链接)。
  2. 统一切换方法:用toggleView(item)代替原来的两个方法,点击时传入当前项,直接翻转它的状态,确保每个Div的切换互不干扰。
  3. 条件显示控制:用*ngIf根据isChartVisible的值,精准控制每个链接和内容区域的显示/隐藏,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:43:46