How To Detect Breakpoints Using the Angular CDK

In this blog, you will apply the CDK’s layout module in Angular projects.

Introduction:

The Angular CDK has a layout package with services to detect viewport sizes and matches against media queries. This allows you full control over the UI and to adapt to different screen sizes.

*Note: This tutorial was verified with Node v16.6.1, npm 7.20.3, @angular/core v12.2.0, and @angular/cdk v12.2.0.

Setting Up the Project:

You can use @angular/cli to create a new Angular Project.

In your terminal window, use the following command:

$ ng new AngularBreakpointsExample --style=css --routing=false --skip-tests

This will configure a new Angular project with styles set to “CSS” (as opposed to “Sass”, Less”, or “Stylus”), no routing, and skipping tests.

Navigate to the newly created project directory:

$ cd AngularBreakpointsExample

Next, install @angular/cdk:

$ npm install @angular/cdk@12.2.0

Then import the layout module and add it to your NgModule’s list of imports: (app.module.ts)

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LayoutModule } from '@angular/cdk/layout';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    LayoutModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

You can now start using the available services and utilities in your components. Let’s discuss each of them.

Using BreakpointObserver.observeand BreakpointState

The observation method returns an observable of type Breakpointstate and can be used to observe when the viewport changes between matching a media query or not.

Here’s an example where a message is logged to the console if the viewport size changes between being less than 500px and equal to or more than 500px: (app.component.ts)

import { Component, OnInit } from '@angular/core';
import {
  BreakpointObserver,
  BreakpointState
} from '@angular/cdk/layout';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(public breakpointObserver: BreakpointObserver) {}

  ngOnInit() {
    this.breakpointObserver
      .observe(['(min-width: 500px)'])
      .subscribe((state: BreakpointState) => {
        if (state.matches) {
          console.log('viewport width is 500px or greater!');
        } else {
          console.log('viewport width is less than 500px!');
        }
      });
  }
}

The Breakpointstate interface gives us a boolean property called matches:

Using Breakpoints:

Instead of using hand-written media queries, we can also make use of the Breakpoints object, which gives us keys for common breakpoints:(app.component.ts)

import { Component, OnInit } from '@angular/core';
import {
  BreakpointObserver,
  Breakpoints,
  BreakpointState
} from '@angular/cdk/layout';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(public breakpointObserver: BreakpointObserver) {}

  ngOnInit() {
    this.breakpointObserver
      .observe([Breakpoints.Small, Breakpoints.HandsetPortrait])
      .subscribe((state: BreakpointState) => {
        if (state.matches) {
          console.log(
            'matches small viewport or handset in portrait mode.'
          );
        }
      });
  }
}

This example uses the predefined breakpoints for Breakpoints.Small and Breakpoints.HandsetPortrait.

Using BreakpointObserver.isMatched

For one-off matching, we can use the is matching method instead.

import { Component, OnInit } from '@angular/core';
import {
  BreakpointObserver,
  BreakpointState
} from '@angular/cdk/layout';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(public breakpointObserver: BreakpointObserver) {}

  ngOnInit() {
    if (this.breakpointObserver.isMatched('(min-height: 40rem)')) {
      console.log('Viewport has a minimum height of 40rem!');
    }
  }
}

This will log a message if the viewport is at least 40rem tall when the component initializes.

Using MediaMatcher

MediaMatcher is a service that wraps around JavaScript’s matchMedia. As with BreakpointObserver.observe, it can also be used to observe changes in the viewport size against a given media query.

Here is an example that checks if min-width is 500px wide:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { MediaMatcher } from '@angular/cdk/layout';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  matcher!: MediaQueryList;

  constructor(public mediaMatcher: MediaMatcher) {}

  ngOnInit() {
    this.matcher = this.mediaMatcher.matchMedia('(min-width: 500px)');

    this.matcher.addEventListener('change', this.myListener);
  }

  ngOnDestroy() {
    this.matcher.removeEventListener('change', this.myListener);
  }

  myListener(event: { matches: any; }) {
    console.log(event.matches ? 'match' : 'no match');
  }
}

The difference with BreakpointObserver.observe is that MediaMatcher gives us access to the native MatchQueryList object, which may be needed in certain scenarios.

Now you have everything you need to react or adapt your UI to different viewport sizes in Angular.

I hope you guys understand how I can do this. Let me know if you face any difficulties.

You can watch my previous blog here.

Happy Coding {;} ????

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories