yodalr
yodalr

Reputation: 10932

Angular 2 - how to create a global service that I only need to load once

What would you suggest is the easiest method for achieving this. I want to create a global service or directive that checks the screen width, so I could use it like this

<div *ngIf="screenSize < 1024">mobile element</div>.

What would be the best approach?

Upvotes: 0

Views: 172

Answers (1)

Niles Tanner
Niles Tanner

Reputation: 4041

Pure CSS

I suggest @media queries

@media (min-width: 1024px) {
  .mobile-element {
    display: none;
  }
}

and the HTML

<div class="mobile-element">mobile element</div>

With angular service

if you must do it in Angular or you are trying to prevent elements from loading you could make a global service:

import {Injectable} from '@angular/core';

@Injectable()

export class ScreenSizeService{
      innerHeight = (window.innerHeight);
      innerWidth = (window.innerWidth);
}

Inject it in the app.module.ts under providers (so it only loads once)

Inject the service into your component:

import {ScreenSizeService} from 'path_to_service';
...
export class SomeComponent{
  constructor(public screenSizeService: ScreenSizeService){} //injecting the service
}

Then use it in the HTML

<div *ngIf="screenSizeService.innerWidth < 1024">mobile element</div>

Upvotes: 2

Related Questions