Angular 中嵌套数组的网格

问题描述 投票:0回答:1
css angular layout css-grid ngfor
1个回答
0
投票

我们只需要一组内部 div。你有一个嵌套的 div 结构,所以它弄乱了布局。我使用

ng-container
作为内部 for 循环,
ng-container
的特殊之处在于它不会在 HTML 中创建元素,因此我们可以使用它来运行两个 for 循环并创建一组 div。

此外,当您创建属性时

[style.grid-template-columns]="'repeat('+outerArray.length+', 1fr)'" 
,请确保您清楚地区分字符串和 JavaScript 变量。

之前的代码只会将

repeat(outerArray.length, 1fr)
渲染为字符串,而不是插入outerArray长度,所以我将代码更改为
'repeat('
(字符串)+
outerArray.length
(数字)+ ', 1fr)'(字符串)

我们还需要

[style.grid-template-rows]
,其配置与列相同。

如果您希望所有行具有相同的高度,请使用提供的带注释的 CSS,它会向元素添加省略号并使所有单元格具有相同的高度!

完整代码:

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  styles: [`
  #container {
    display: grid;
  }
  /* .same-height {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  } */
  `],
  template: `
    <div id="container" [style.grid-template-columns]="'repeat('+outerArray.length+', 1fr)'" [style.grid-template-rows]="'repeat('+outerArray.length+', 1fr)'" [style.columnGap.rem]="1" *ngIf="outerArray.length != 0">
      <ng-container class="outerArray" *ngFor="let inner of outerArray">
        <div *ngFor="let item of inner" style="background-color: red;color: white; margin-bottom:2px;" class="same-height">
          {{item}}
        </div>
      </ng-container>
    </div>
  `,
})
export class App {
  outerArray = [
    ['short', 'bit longer', 'example value'],
    ['not so long, but longer string', 'short words', 'bitLonger twoWords'],
    ['shorter array', 'different lengths of strings'],
    ['another shorter array', 'string'],
  ];
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.