How to write media query in typescript file?

Viewed 5902

I need to change media query in ts file because my variable visible showSideBar if width < 580px = true. I need solution how to know in ts file when is resolution below 580px to set variable to true.

TS.file

  showSideBar = false;

SCSS. file

.aside-bar {
   @media(max-width: 580px) {
     ....any value
  }
}
2 Answers

You can use something like this in plain js. https://www.w3schools.com/howto/howto_js_media_queries.asp

You can use .matches in the example to set your value.

function doCheck(query) {
  if (query.matches) { // If media query matches
    document.querySelector('.aside-bar').innerHTML = 'red'
  } else {
    document.querySelector('.aside-bar').innerHTML = 'blue'
  }
}

const query = window.matchMedia("(max-width: 400px)")
doCheck(query) // Call listener function at run time
query.addListener(doCheck) // Attach listener function on state changes
.aside-bar {
  width: 100px;
  height: 100px;
  color: white;
  background: blue;
}
  
@media(max-width: 400px) {
  .aside-bar {
    background: red;
  }
}
<div class="aside-bar">aside bar</div>

I would use the angular cdk layout observers to get an observable

https://material.angular.io/cdk/layout/overview

@Component({...})
class MyComponent {
  constructor(breakpointObserver: BreakpointObserver) {
    breakpointObserver.observe([
      Breakpoints.HandsetLandscape,
      Breakpoints.HandsetPortrait
    ]).subscribe(result => {
      if (result.matches) {
        this.activateHandsetLayout();
      }
    });
  }
}
@Component({...})
class MyComponent {
  constructor(mediaMatcher: MediaMatcher) {
    const mediaQueryList = mediaMatcher.matchMedia('(min-width: 1px)');
  }
}
Related