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
}