Rimika
Rimika

Reputation: 187

Angular CDK Layout - How to include BreakPointObserver globally across the project

I am setting up a new project with latest Angular.I am using Angular Material for this. I am using BreakpointObserver from @angular/cdk/layout. I am able to add that succesfully to one of my component.But I want to add it globally to my project so that all the components/modules can use web/tablet/mobile breakpoints for different DOM manipulation.

I am able to add that to the app.component.ts , but I am expecting to write a directive or something. Not service because BreakpointObserver is already a service.

What would be the best approach to add BreakPointObserver observables globally in the project. Do not want to add isHandset$ observables everytime in each component's ts file

Upvotes: 10

Views: 2851

Answers (1)

Jorge J Lorenzo
Jorge J Lorenzo

Reputation: 141

I think your idea of using some kind of custom directive would be a good solution. For example, in the case you want to add/remove components of the DOM, you could define only one structural directive that handle adding/removing its host, depending on the viewport dimension using the BreakpointObserver service.

To accomplish that you could define something like this:

@Directive({
    selector: '[contentForSmallScreen]'
})
export class ContentForSmallScreenDirective implements OnDestroy  {

  constructor(
     private templateReference: TemplateRef<any>,
     private viewContainerRef: ViewContainerRef,
     private breakpointObserver: BreakpointObserver
  ) {
      this.breakpointObserver
          .observe([tablet,mobile])
          .pipe(pluck('matches'), distinctUntilChanged())
          .subscribe(this.showHideHost);  
  }

  private showHideHost = (matches: boolean) => {
      matches 
          ? this.viewContainerRef.createEmbeddedView(this.templateReference)
          : this.viewContainerRef.clear();
  }

  ngOnDestroy(): void {
    this.breakpointObserver.ngOnDestroy();
  }
}

And then after declare it at your NgModule, it can be used with any component/html element you wanna add/remove from the DOM depending on if the viewport's dimension meet the tablet and mobile viewport specs.

<app-any-component *contentForSmallScreen></app-any-component>

👨‍💻 StackBlitz example

Upvotes: 1

Related Questions