Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement of deprecated MediaQueryList.addListener() event in Angular 8

The Mozilla Developers Network docs say MediaQueryList.addListener() is deprecated.

Though it's working in my (Angular 8) code, the linting in VS Code is warning about deprecation.

What's the replacement for MediaQueryList.addListener()?

like image 264
Chaitanya Avatar asked Aug 06 '19 07:08

Chaitanya


2 Answers

Quoting from the MDN docs about MediaQueryList:

MediaQueryList.addListener() Adds a listener to the MediaQueryListener that will run a custom callback function in response to the media query status changing. This is basically an alias for EventTarget.addEventListener(), for backwards compatibility purposes.

addEventListener needs an event type as the first argument, so it becomes this:

// deprecated: MediaQueryList.addListener(listener);
MediaQueryList.addEventListener('change', listener);

The same stands true for removeListener():

// deprecated: MediaQueryList.removeListener(listener);
MediaQueryList.removeEventListener('change', listener);
like image 122
mutil Avatar answered Oct 13 '22 09:10

mutil


Do this to ensure compatibility with browsers that do not support MediaQueryList.addEventListener:

const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')

if (darkModeQuery.addEventListener) {
  darkModeQuery.addEventListener('change', setDarkMode)
} else {
  darkModeQuery.addListener(setDarkMode)
}
like image 1
Aparajita Avatar answered Oct 13 '22 07:10

Aparajita