Angular Material 7 – Grid List

Angular Material 7 – Grid List

在大多数 Web 应用中,呈现数据的方式往往是以列表形式呈现的,这种方式总是有些单调。但是在某些情况下,我们需要将我们的数据以网格形式呈现。在这种情况下,Angular MaterialGrid List 组件就非常适合使用。在这篇文章中,我们将详细介绍 Angular Material 7 中的 Grid List 组件,并提供一些例子来让你更好地理解。

什么是 Grid List?

Grid List 是一个基于 Flex 布局的组件,可以用于展示纵向和横向的数据列表。它包含多种选项,使您可以根据自己的需求呈现数据。

下面是一个简单的 Grid List 例子:

<mat-grid-list cols="2" rowHeight="100px">
  <mat-grid-tile *ngFor="let tile of tiles" [colspan]="tile.cols" [rowspan]="tile.rows">
    {{tile.text}}
  </mat-grid-tile>
</mat-grid-list>

在这个例子中,我们使用 cols 属性设置为 2,来让 Grid List 中的元素分为两列展示。我们也使用 rowHeight 属性,将每个元素的高度设置为 100px,这样它们就会以同样的高度出现。最后,我们使用 ngFor 指令来迭代一个数组,并使用 colspanrowspan 属性来设置每个元素所占据的列和行的数量。

Grid List 的 API

在本节中,我们将更加深入地了解 Grid List 的 API。您可以按照自己的需要,在应用程序中使用这些选项。

mat-grid-list

mat-grid-listGrid List 的容器组件。它有以下属性:

  • cols:设置 Grid List 中列的数量。
  • rowHeight:设置 Grid List 中每个元素的高度。
  • gutterSize:根据像素值设置 Grid List 中元素之间的间隔大小。

以下是一个具有三列,并且带有 30px 间隔的 Grid List

<mat-grid-list cols="3" gutterSize="30">
  <!-- 其他元素 -->
</mat-grid-list>

mat-grid-tile

mat-grid-tileGrid List 中的每个元素。它有以下属性:

  • colspan:设置一行中 mat-grid-tile 元素所占用的列的数量。
  • rowspan:设置一列中 mat-grid-tile 元素所占用的行的数量。
  • col:设置元素在横向的位置。
  • row:设置元素在纵向的位置。
  • style:设置元素的 CSS 样式。

以下是一个具备 2 列和 2 行的 Grid List 中的一个元素,占据了 2 行和 1 列:

<mat-grid-list cols="2" rowHeight="100px">
  <mat-grid-tile rowspan="2" colspan="1" >
    <!-- 其他元素 -->
  </mat-grid-tile>
</mat-grid-list>

Grid List 的示例

在这一部分,我们将涵盖一些使用 Grid List 的例子。这些例子将有助于让您更好地了解如何使用 Grid List,并从其他人的实现中汲取灵感。

网格布局

下面的例子展示了如何使用 mat-grid-list 来创建一个基本的网格布局,其中包含一些图像和文本:

<mat-grid-list cols="2" rowHeight="250px" gutterSize="10">
  <mat-grid-tile *ngFor="let item of items" [colspan]="item.cols" [rowspan]="item.rows">
    <mat-card class="example-card">
      <img mat-card-image src="{{item.img}}" alt="{{item.name}}">
      <mat-card-content>
        <h2 mat-card-title>{{item.name}}</h2>
        <p mat-card-subtitle>{{item.desc}}</p>
        <p mat-card-subtitle>{{item.date}}</p>
      </mat-card-content>
    </mat-card>
  </mat-grid-tile>
</mat-grid-list>

如上所述,cols="2" 属性将元素分为两列。这个例子还使用 <mat-card> 组件作为 Grid List 中的元素,以展示图像和文本。

瀑布流布局

接下来,这个例子展示了如何使用 mat-grid-list 来创建一个瀑布式布局,其中包含了不同大小和形状的元素:

<mat-grid-list cols="4" rowHeight="120px" [style.height]="totalHeight">
  <mat-grid-tile *ngFor="let item of items" [colspan]="item.cols" [rowspan]="item.rows">
    <div class="example-grid-tile-content"
         [ngStyle]="{'background': item.color}"
         [style.height.px]="item.rows * 40"
         [style.width.%]="item.cols * 25">
      {{item.text}}
    </div>
  </mat-grid-tile>
</mat-grid-list>

该示例中 cols="4" 属性将元素分为四列,但这次它们可以有不同的大小和形状。 这个例子使用 CSS 样式来设置不同的背景颜色和元素的大小。

结论

在本文中,我们介绍了 Angular Material 7 中的 Grid List 组件,并提供了一些例子来展示如何使用这个组件。借助这些示例,您现在应该可以使用 Grid List 来呈现您的数据了。如果您想了解更多信息,请查看 Angular Material 文档。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程