Search code examples
htmlangulartypescriptmobiledesktop

detect is user on mobile typescript without send new request


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?


Solution

  • 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);
    }