Benjamin Barbé
Benjamin Barbé

Reputation: 271

Angular 7 responsive layout using Material Grid

I'am setting up a web application, and i want to implement the mobile version with the responsivity.

I'm using Angular 7, and angular material 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>

I have one gridlist with 12 cols which contains 3 tiles :

A- 6 (6/12)

B- 3 (3/12)

C- 3 (3/12)

WEB

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

AAAAAA BBB CCC

When i get the phone size i want to have : one gridlist with 12 cols which contains 3 tiles :

A- 12 (12/12)

B- 6 (6/12)

C- 6 (6/12)

MOBILE

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

AAAAAAAAAAAA

BBBBBB-CCCCCC

Sorry for my english ;) Thanks

Upvotes: 4

Views: 11799

Answers (2)

G. Tranter
G. Tranter

Reputation: 17918

In grid layouts, only ratios really matter (not actual column counts). In your case, the ratios between tile sizes doesn't change - the first tile is always twice as wide as the second and third tiles. So you can mathematically reduce your mobile layout to:

A- 6 (6/6)
B- 3 (3/6)
C- 3 (3/6)

Now, the tile colspan values are the same for both layouts, the only difference is the number of columns. This makes it simpler to implement a responsive design, because you only need to change the cols value between 12 and 6.

Bind the cols value input to an expression:

<mat-grid-list [cols]="isMobile ? 6 : 12">...

Use CDK's Layout module to detect device changes:

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;
    });
  }

  ...
}

You can also customize the break point based on screen size:

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

Upvotes: 11

Benjamin Barb&#233;
Benjamin Barb&#233;

Reputation: 271

To customise the breakpoint :

breakpointObserver.observe(['(min-width: 500px)'])

Upvotes: 0

Related Questions