Angular

How to Use the Angular CDK to Identify Breakpoints

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

Introduction:

The Angular CDK provides a layout package that includes services for detecting viewport sizes and matching media queries. This gives you complete control over the UI and allows you to adjust it to different screen sizes.

Let’s start the project setting up:

We can use @angular/CLI to create a new Angular Project for this demo.

Use the following command in your terminal window:

$ ng new AngularBreakpointsDemo

This will create a new Angular project with CSS styles (rather than Sass, Less, or Stylus), no routing, and no tests.

Go to the newly created project folder:

$ cd AngularBreakpointsDemo

Now, We can install @angular/CDK:

$ npm install @angular/cdk

Then import the layout module and add it to the list of imports in your NgModule: (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({
  imports: [ 
   LayoutModule,
   BrowserModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now we can start using the services in our components.

BreakpointObserver.observe and BreakpointState are two methods for detecting breakpoints.

The observation method returns a Breakpointstate observable, which may be used to track whether the viewport matches a media query or not.

In this example, if the viewport size changes from less than 500px to equal to or more than 500px, a message is recorded to the console: (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!');
        }
      });
  }
}

Matches, which is a boolean property in the Breakpointstate interface.

How to use Breakpoints:

We may utilize the Breakpoints object instead of hand-writing media queries because it provides keys for typical 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'
          );
        }
      });
  }
}

this example uses predefined breakpoints. Small and Breakpoints.HandsetPortrait.

BreakpointObserver.isMatched is a method for determining whether or not a breakpoint is matched.

Instead, we can utilize the is matching method for one-time matching.

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

How to use MediaMatcher using breakpoints.

MediaMatcher, which is a wrapper for JavaScript’s matchMedia method. It can be used to track changes in viewport size against a media query, just like BreakpointObserver.observe.

Here’s an example of how to see if min-width is 500 pixels 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 mediaMatcherService: MediaMatcher) {}

  ngOnInit() {
    this.matcher = this.mediaMatcherService.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 between MediaMatcher and BreakpointObserver.observe is that MediaMatcher offers us access to the native MatchQueryList object, which is useful in some cases.

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

Nayan Raval

Nayan Raval is a MEAN Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. Key Areas Of Expertise: • ASP.NET Core MVC • ASP.NET Core Web API • C# • ASP.NET MVC 5 • Angular All versions • HTML5 • CSS3 / SCSS • Bootstrap • JavaScript • Azure • JQuery Databases and related • Microsoft SQL server MSSQL • PostgreSQL • Entity Framework (EF) • LINQ UI Frameworks • Kendo UI • Telerik • JQuery UI • Prime NG and Material UI API Integration • SignalR • DateDog • Twilio Voice Call And Message • Stripe • SendGrid (Email Camping) • Checkr • Zoom Video Call • Auth0 • Elastic Search • Quartz - Scheduler • JWT Token • Google Calendar

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago