If you want to make your Angular project responsive, consider using the angular/breakpoints-angular-cdk library.
Here are the steps to follow:
First, run the following command in your terminal:
npm install @angular/cdk
Next, import the layout module and add it to the list of imports in your NgModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { LayoutModule } from '@angular/cdk/layout';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
LayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
After that, you can start using it in your component by importing the necessary classes from @angular/cdk/layout
:
import { Component, OnInit } from '@angular/core';
import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout';
@Component({ ... })
export class AppComponent implements OnInit {
public showContainer: boolean;
constructor(public breakpointObserver: BreakpointObserver) {}
ngOnInit() {
this.breakpointObserver.observe(['(min-width: 400px)'])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.showContainer = true;
} else {
this.showContainer = false;
}
});
}
}
For updated information on how to handle screen sizes in newer versions of Angular, be aware of the constant provided for screen size identification:
UPDATE: If you're using a newer version of Angular, utilize the Breakpoints constant:
import { Component, OnInit } from '@angular/core';
import { BreakpointObserver, BreakpointState, Breakpoints } from '@angular/cdk/layout';
@Component({ ... })
export class AppComponent implements OnInit {
public showContainerInTablet: boolean;
public showContainerInHandset: boolean;
constructor(public breakpointObserver: BreakpointObserver) {}
ngOnInit() {
this.breakpointObserver.observe([
Breakpoints.TabletPortrait,
Breakpoints.HandsetLandscape
]).subscribe((state) => {
const breakpoints = state.breakpoints;
this.showContainerInHandset = false;
this.showContainerInTablet = false;
if (breakpoints[Breakpoints.TabletPortrait]) {
this.showContainerInTablet = true;
console.log("Screens match TabletPortrait");
} else if (breakpoints[Breakpoints.HandsetLandscape]) {
this.showContainerInHandset = true;
console.log("Screens match HandsetLandscape");
}
});
}
}
For more detailed tutorials on responsive design in Angular, visit the official Angular website.