首页 > 解决方案 > 在角材料中显示多个网格

问题描述

我正在尝试在一页中显示 8 个小网格。每个网格有 2 列和
4 行,每个单元格大约 2 个单词。

<mat-grid-list cols="2">
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
            <mat-grid-tile>
                hello world
            </mat-grid-tile>
        </mat-grid-list>

我对如何以令人愉悦的方式安排它们的其他建议持开放态度,但我的想法是:

我真的不知道该怎么做,这个设置和条件的正确方法是什么?

我什至无法在一行上显示 2 个网格,似乎默认情况下一个网格会占用所有可用的页面宽度。

标签: angularangular-materialangular6

解决方案


您可以使用 FlexLayout 模块来监听媒体变化并根据屏幕大小设置列数。然后将cols值绑定到列数变量。这是一个 Stackblitz 示例

HTML:

<mat-grid-list [cols]="columns" rowHeight="2:1">
  <mat-grid-tile>hello world</mat-grid-tile>
  <mat-grid-tile>hello world</mat-grid-tile>
  <mat-grid-tile>hello world</mat-grid-tile>
  <mat-grid-tile>hello world</mat-grid-tile>
  <mat-grid-tile>hello world</mat-grid-tile>
  <mat-grid-tile>hello world</mat-grid-tile>
  <mat-grid-tile>hello world</mat-grid-tile>
  <mat-grid-tile>hello world</mat-grid-tile>
</mat-grid-list>

TS:

import { Component, OnDestroy } from '@angular/core';
import { MediaChange, ObservableMedia } from '@angular/flex-layout';
import { Subscription } from 'rxjs';

/**
 * @title Flexible grid-list
 */
@Component({
  selector: 'grid-list-flexible-example',
  styleUrls: ['grid-list-flexible-example.css'],
  templateUrl: 'grid-list-flexible-example.html',
})
export class GridListFlexibleExample implements OnDestroy {
  watcher: Subscription;
  columns: number = 4;

  constructor(media: ObservableMedia) {
    this.watcher = media.subscribe((change: MediaChange) => {
      if (change) {
        if (change.mqAlias == 'xs') {
          this.columns = 2;
        } else if (change.mqAlias == 'sm') {
          this.columns = 3;
        } else {
          this.columns = 4;
        }
      }
    });
  }

  ngOnDestroy() {
    this.watcher.unsubscribe();
  }

}

推荐阅读