使用材质网格的 Angular 7 响应式布局

Ben*_*rbé 1 grid material-design angular-material responsive angular

我正在设置一个 Web 应用程序,我想实现具有响应性的移动版本。

我使用的是 Angular 7 和 Angular 材质 7.2。

<mat-grid-list cols="12">
  <mat-grid-tile  [colspan]="6">

    <h1 class="title">Title</h1>

  </mat-grid-tile>
  <mat-grid-tile [colspan]="3">

    <h2 class="date">Date</h2>

  </mat-grid-tile>
  <mat-grid-tile [colspan]="3">

    <h1 class="price">price€</h1>

  </mat-grid-tile>
</mat-grid-list>
Run Code Online (Sandbox Code Playgroud)

我有一个包含 3 个图块的 12 个列的网格列表:

A- 6 (6/12)

B- 3 (3/12)

C- 3 (3/12)

网络

<-------- 12 -------->

AAAAAA BBB CCC

当我得到我想要的手机尺寸时:一个包含 3 个图块的 12 列网格列表:

A- 12 (12/12)

B- 6 (6/12)

C- 6 (6/12)

移动的

<-------- 12 -------->

AAAAAAAAAAAA

BBBBBB-中交

对不起我的英语 ;) 谢谢

G. *_*ter 7

在网格布局中,只有比率真正重要(不是实际的列数)。在您的情况下,图块大小之间的比率不会改变 - 第一个图块的宽度始终是第二个和第三个图块的两倍。因此,您可以在数学上将移动布局简化为:

A- 6 (6/6)
B- 3 (3/6)
C- 3 (3/6)
Run Code Online (Sandbox Code Playgroud)

现在,colspan两种布局的图块值相同,唯一的区别是列数。这使得实现响应式设计更简单,因为您只需要更改cols12 和 6 之间的值。

cols值输入绑定到表达式:

<mat-grid-list [cols]="isMobile ? 6 : 12">...
Run Code Online (Sandbox Code Playgroud)

使用CDK 的 Layout 模块检测设备变化:

import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
...
class MyComponent {

  public isMobile: boolean = false;

  constructor(breakpointObserver: BreakpointObserver) {
    breakpointObserver.observe([
      Breakpoints.Handset
    ]).subscribe(result => {
      this.isMobile = result.matches;
    });
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

您还可以根据屏幕大小自定义断点:

breakpointObserver.observe([
  '(max-width: 599px)'
]).subscribe(result => {
  this.isMobile = result.matches;
});
Run Code Online (Sandbox Code Playgroud)