【问题标题】:angular2 material design how to fill mat-card dynamically from dataSource?angular2材料设计如何从dataSource动态填充mat-card?
【发布时间】:2020-08-05 07:38:47
【问题描述】:

我希望这里有人可以帮助我。我有一个 dataSource 数组,我想将此数据动态写入几个 mat-card 元素。例如,我有一个大小为 200 的数组。现在我想写入一定数量的数据,例如 30 个数据到一个垫卡中,然后用接下来的 30 个数据写入一个新的垫卡,依此类推,直到所有我的数据源中的数据被写入垫卡。我用 ngFor 试过这个,但我对编程知之甚少,所以我想问你是否有适合我的解决方案?非常感谢

【问题讨论】:

    标签: angular typescript angular-material ngfor angular-ng-if


    【解决方案1】:

    您可以通过将原始数组中的数据分块到一个二维数组中来做到这一点,其中第 0 项是包含前 30 项的数组,第 1 项是包含后 30 项等的数组。例如,如果您的数组是:

    ['this', 'is', 'some', 'data', 'that', 'will', 'be', 'rendered', 'in', 'the', 'cards']
    

    分块数组(假设块大小为 3)将是:

     [['this', 'is', 'some'], ['data', 'that', 'will'], ['be', 'rendered', 'in'], ['the', 'cards']]
    

    我已经实现了以下函数来分块数据(只需将3 更改为您想要的任何块大小):

    readonly chunkSize: number = 3;
    
    getChunkedData() {
      var chunkedData = [];
      for (let i = 0; i < this.data.length; i += this.chunkSize) {
        chunkedData.push(this.data.slice(i, i + this.chunkSize));
      }
      return chunkedData;
    }
    

    然后您可以使用ngFor 循环分块数组并将每个项目呈现在一张卡片中:

    <mat-card *ngFor="let data of getChunkedData()">
      <p *ngFor="let item of data">
        {{item}}
      </p>
    </mat-card>
    

    请参阅this StackBlitz 以获得工作演示。

    【讨论】:

      猜你喜欢
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多