Home > Software engineering >  detect is user on mobile typescript without send new request
detect is user on mobile typescript without send new request

Time:12-31

I have value in the typescript file

readonly isMobile: boolean = false;

And inside cosntructor i have this to check is suer on mobile or desktop app version:

    if (window.navigator?.maxTouchPoints > 0) {
        this.isMobile = true;
    }

In the HTML file, I wanna show/hide something if isMobile is true, and everything works but if I'm on the desktop version and I manually resize the screen to become small, isMobile is still false, i need to go inspect the element >> select mobile devices and restart page and then will appear content-based if isMobile is true, can value isMobile be set to true if i resize the screen size to be like mobile screen?

CodePudding user response:

In this case, you can listen for the window resize event and set the isMobile value.

@HostListener('window:resize', ['$event'])
onResize(event) {
  // Check window size and do actions..
}

CodePudding user response:

You can use something like this:

window.onresize = () => {
  let isMobile = false;
  console.log('RESIZING ...', window.innerHeight, window.innerWidth);
  const mobileWidthThreshold = 375; // For example
  if (window.innerWidth <= mobileWidthThreshold) {
    isMobile = true;
  } else {
    isMobile = false;
  }
  console.log(isMobile);
}
  • Related