如何在Bootstrap Table中合并值相同的年份表头单元格?
Bootstrap Table 多层表头合并解决方案
核心问题排查
你之前的代码不生效的核心原因是:Angular框架中绑定colspan这类原生HTML属性时,必须加attr.前缀,否则框架会将其识别为组件自定义输入属性,不会作用到真实DOM上。
第一步:预处理年份分组数据
你需要先将原月份数据按年份分组,统计每个年份对应的月份数量作为colspan的取值:
// 原数据 YearGrid = [ {Month: 'Nov', Year: 2020}, {Month: 'Dec', Year: 2020}, {Month: 'Jan', Year: 2021}, {Month: 'Feb', Year: 2021}, {Month: 'Mar', Year: 2021} ]; // 新增分组后的年份表头数据 yearHeaderList = []; ngOnInit() { // 按年份统计每个年份对应的列数 const yearCountMap = this.YearGrid.reduce((map, item) => { map[item.Year] = (map[item.Year] || 0) + 1; return map; }, {}); // 转换为遍历用的数组 this.yearHeaderList = Object.keys(yearCountMap).map(year => ({ year: Number(year), colspan: yearCountMap[year] })); }
第二步:修改表头模板代码
第一行年份表头遍历分组后的数据,绑定attr.colspan属性;第二行月份表头保持原遍历逻辑即可:
<thead> <tr> <th *ngFor="let yearItem of yearHeaderList" [attr.colspan]="yearItem.colspan"> {{yearItem.year}} </th> </tr> <tr> <th *ngFor="let colItem of YearGrid"> {{colItem.Month}} </th> </tr> </thead>
最终渲染效果
上述代码会自动生成符合预期的合并表头:
- 2020表头单元格跨2列,对应下方Nov、Dec两个月份列
- 2021表头单元格跨3列,对应下方Jan、Feb、Mar三个月份列
内容的提问来源于stack exchange,提问作者sumithra raj
相关产品推荐
相关产品推荐

