【问题标题】:How to display array items across multiple rows in an Angular app如何在 Angular 应用程序中跨多行显示数组项
【发布时间】:2019-07-17 13:52:47
【问题描述】:

在我的 Angular 应用程序中,我的 .ts 文件中有一组公司,这些公司在我的 HTML 中使用 ngFor 显示在以下代码中:

<div class="card-deck">
  <div class="card" *ngFor="let company of companies">
      <div class="card-body">
         <h5 class="card-title">         
             {{ company.companyName }}
          </h5>
       </div>
  </div>
</div>

上面的卡片组在一行中显示了整个公司列表。

例如,如果有 3 家公司,那么它们会在屏幕上显示在一行中。如果有 10 家公司,则显示在一行中。

谁能告诉我需要对我的 TS 或 HTML 进行哪些更改,以便我可以设置每行中的公司数量? IE。一行最多只能显示 3 家公司,然后移动到下一行。

非常感谢。

【问题讨论】:

    标签: html angular twitter-bootstrap typescript


    【解决方案1】:

    作为一种可能的解决方案,您可以从companies 创建多维数组并使用两个*ngFor(遍历行,然后遍历companies)。

    // component.ts
    
    companies = [{
        companyName: 'first'
      },
      {
        companyName: 'second'
      },
      {
        companyName: 'third'
      }
      ...
    ] // for example, ten elements in companies
    
    companiesInRow: number = 3; // number of companies in row
    rows;
    
    ngOnInit() {
      // create multidimensional array
      this.rows = this.companies.reduce((acc, value, index) => {
        if (index % this.companiesInRow == 0 && index !== 0) acc.push([])
          acc[acc.length - 1].push(value)
        return acc;
      }, [[]]);
    }
    
    
    // component.html
    <div class="card-deck" *ngFor="let comps of rows">
      <div class="card" *ngFor="let company of comps">
        <div class="card-body">
          <h5 class="card-title">         
             {{ company.companyName }}
          </h5>
        </div>
      </div>
    </div>
    

    查看stackblitz

    【讨论】:

      【解决方案2】:

      一种简单的方法是在您的卡片div 中添加一些style,例如:

      <div class="card-deck">
        <div class="card" *ngFor="let company of companies" style="width:33%; display: inline-block; text-align: center">
            <div class="card-body">
               <h5 class="card-title">         
                   {{ company.companyName }}
                </h5>
             </div>
        </div>
      </div>
      

      You can view the output of above code here

      【讨论】:

        猜你喜欢
        • 2020-06-05
        • 2020-02-13
        • 2019-04-17
        • 1970-01-01
        • 2021-04-14
        • 1970-01-01
        • 1970-01-01
        • 2017-11-16
        • 1970-01-01
        相关资源
        最近更新 更多