Updated on Kisan Patel
Lets learn how to detect viewport size with the help of angular CDK BreakpointObserver?
First, you’ll want to make sure you have the Angular CDK layout installed into your app:
npm install @angular/cdk
Now, create the directive class file in a terminal window with the CLI command ng generate directive
.
ng generate directive IfViewportSize
The if-viewport-size.directive.ts is as follows
if-viewport-size.directive.ts
import { Directive, OnDestroy, Input, ViewContainerRef, TemplateRef } from '@angular/core'; import { BreakpointObserver, Breakpoints, BreakpointState } from '@angular/cdk/layout'; import { Subscription } from 'rxjs'; type Size = 'small' | 'medium' | 'large'; const config = { small: [Breakpoints.Small, Breakpoints.XSmall], medium: [Breakpoints.Medium], large: [Breakpoints.Large, Breakpoints.XLarge], }; @Directive({ selector: '[ifViewportSize]', }) export class IfViewportSizeDirective implements OnDestroy { private subscription = new Subscription(); @Input('ifViewportSize') set size(value: Size) { this.subscription.unsubscribe(); this.subscription = this.observer.observe(config[value]) .subscribe(this.updateView); } constructor( private observer: BreakpointObserver, private vcRef: ViewContainerRef, private templateRef: TemplateRef<any> ) {} updateView = ({ matches }: BreakpointState) => { if (matches && !this.vcRef.length) { this.vcRef.createEmbeddedView(this.templateRef); } else if (!matches && this.vcRef.length) { this.vcRef.clear(); } }; ngOnDestroy() { this.subscription.unsubscribe(); } }
app.module.ts
import { NgModule } from '@angular/core';
... @NgModule({ imports: [ ... ], declarations: [ ... IfViewportSizeDirective ], bootstrap: [AppComponent] }) export class AppModule { }
Next, use the new ifViewportSize
directive as follow:
app.component.html
<h2 class="title">Hello {{name}}</h2> <div *ifViewportSize="'large'">PC</div> <div *ifViewportSize="'medium'">Tablet</div> <div *ifViewportSize="'small'">Mobile </div>