• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Angular / DeviceService

DeviceService

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

@Injectable({
providedIn: 'root',
})
export class DeviceService {
private readonly mqMobile = window.matchMedia('(max-width: 767px)');
private readonly mqTablet = window.matchMedia('(min-width: 768px) and (max-width: 1023px)');
private readonly mqDesktop = window.matchMedia('(min-width: 1024px)');

public readonly isMobile = signal(this.mqMobile.matches);
public readonly isTablet = signal(this.mqTablet.matches);
public readonly isDesktop = signal(this.mqDesktop.matches);

private readonly mobileListener = (e: MediaQueryListEvent): void => this.isMobile.set(e.matches);
private readonly tabletListener = (e: MediaQueryListEvent): void => this.isTablet.set(e.matches);
private readonly desktopListener = (e: MediaQueryListEvent): void => this.isDesktop.set(e.matches);

public constructor() {
// Listener bekötés
this.mqMobile.addEventListener('change', this.mobileListener);
this.mqTablet.addEventListener('change', this.tabletListener);
this.mqDesktop.addEventListener('change', this.desktopListener);
}
}

Use in component

export class News {
public readonly news = signal(MockNews.data.blocks);

private readonly device = inject(DeviceService);

public readonly isMobile = this.device.isMobile;
public readonly isDesktop = this.device.isDesktop;
}

Use in template

@if (isMobile()) {
mobile
} @else {
desktop
}

Filed Under: Angular

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved