Detect Breakpoint at Angular

2019/2/11 min read
bookmark this
Responsive image

Detect breakpoint by use @angular/cdk

breakpoint usually is CSS, you write media query for different style for different view. However, sometime you might want to do that in Javascript instead of CSS. At this blog, we'll use @angular/cdk at Angular Universal App project.

First intall @angular/cdk


"@angular/cdk": "^7.3.3",

Add Layout Module to root angular module


import { LayoutModule } from "@angular/cdk/layout";

@NgModule({
  declarations: [AppComponent, HomeComponent],
  imports: [
    BrowserModule.withServerTransition({ appId: "my-app" }),
    RouterModule.forRoot([
      { path: "", component: HomeComponent, pathMatch: "full" },
      { path: "lazy", loadChildren: "./lazy/lazy.module#LazyModule" },
      { path: "lazy/nested", loadChildren: "./lazy/lazy.module#LazyModule" }
    ]),
    TransferHttpCacheModule,
    LayoutModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Use @angular/cdk at Angular component


  ngOnInit(): void {
    this.breakpointObserver
      .observe(["(min-width: 500px)"])
      .subscribe((state: BreakpointState) => {
        if (state.matches) {
          console.log("Viewport is 500px or over!");
        } else {
          console.log("Viewport is getting smaller!");
        }
      });
  }

References

https://alligator.io/angular/breakpoints-angular-cdk/