typescript 如何用角离子三柱网格显示带边界动态数据

gv8xihay  于 2023-01-21  发布在  TypeScript
关注(0)|答案(1)|浏览(119)

我有动态数据,显示在无序列表中,离子角如下

<div *ngIf="personNameArray.length">{{'Selected People:'|translate}}</div>
              <div class="ion-margin-start" *ngIf="personNameArray.length">
                <ul>
                  <li *ngFor="let name of personNameArray">
                    {{name}}
                  </li>
                </ul>
              </div>

我需要在具有平均分布记录的3列网格中显示“personNameArray”数据。我应该如何操作?请指导。谢谢

2ledvvac

2ledvvac1#

将数组值均匀分布在多列中

我创建了两个解决方案:一种是从左到右填充值,另一种是从上到下填充值。这两种解决方案都是通用的,因为您只需更改numberOfColumns-变量的值,UI就会相应地进行调整。

变量1-从左到右填充值

预期输出:

'1 Tom'    | '2 Luke'  | '3 Torsten' |
'4 John'   | '5 Mike'  | '6 Emily'   |
'7 Jessica'| '8 Jacob' | '9 Madison' |
'10 Ethan' | '11 Matt' |
    • TS文件:**
numberOfColumns = 3; // The number of columns can be changed as desired

names: string[] = ["1 Tom", "2 Luke", "3 Torsten", "4 John", "5 Mike", "6 Emily",
                   "7 Jessica", "8 Jacob", "9 Madison", "10 Ethan", "11 Matt" ];

get gridSpecification(): string {
    return `repeat(${this.numberOfColumns}, 1fr)`;
}
    • HTML文件:**
<ul [style.display]="'grid'"
    [style.grid-template-columns]="gridSpecification">

    <li *ngFor="let name of names">
        {{name}}
    </li>
</ul>

变量2-从上到下填充值

预期输出:

'1 Tom'    | '5 Mike'    | '9 Madison' |
'2 Luke'   | '6 Emily'   | '10 Ethan'  |
'3 Torsten'| '7 Jessica' | '11 Matt'   |
'4 John'   | '8 Jacob'   |
    • TS文件:**

让我们重新排列数组元素,使解决方案1的html部分可以重用:

numberOfColumns = 3; // The number of columns can be changed as desired

names: string[] = ["1 Tom", "2 Luke", "3 Torsten", "4 John", "5 Mike", "6 Emily",
                   "7 Jessica", "8 Jacob", "9 Madison", "10 Ethan", "11 Matt" ];

reOrderedNames: string[] = [];

get gridSpecification(): string {
    return `repeat(${this.numberOfColumns}, 1fr)`;
}

ngOnInit(): void {
    const arrayOfBatches = this.splitIntoBatches(this.names, this.numberOfColumns);
    this.reOrderedNames = this.zip(arrayOfBatches).flat();
}

private splitIntoBatches(arr: string[], numberOfBatches: number): string[][] {
    // 'max batch size' equals 'max column length'
    const maxBatchSize = Math.ceil(arr.length / numberOfBatches);

    // 'number of batches' equals 'number of columns'
    return  Array.from({ length: numberOfBatches },
                        (_, i) => arr.slice(i * maxBatchSize, (i + 1) * maxBatchSize));
}

private zip(arr: string[][]): string[][] {
    // 'max array length' equals 'max column length'
    const maxArrayLength = Math.max(...arr.map(a => a.length));

    return Array.from({ length: maxArrayLength },
                     (_, i) => arr.filter(a => !!a[i]).map(a => a[i]));  
}
    • HTML文件:**
<ul [style.display]="'grid'"
    [style.grid-template-columns]="gridSpecification">

    <li *ngFor="let name of reOrderedNames">
        {{name}}
    </li>
</ul>

相关问题