简体   繁体   中英

What is the best practice to listening to DOM event in Angular 8?

I want to listening 'storage' event from window in Angular 8. So, what is the best practice to do what below in Angular?

window.addEventListener('storage', () => {
});

One way is using Renderer2, but is there a better way?

You can use RxJS for this. From the Official documentation ,

RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on.

Also RxJS uses pure functions, which will minimize the risk of errors.

import { Observable, fromEvent } from 'rxjs';

var storage = Observable.fromEvent(window, 'storage').subscribe(res => console.log(res));

you can attach host listener to local storage as Storage interface emits storage event on global objects which it affects.

something like this

import { KeyboardEvent } from '@angular/core';

@Component({
  ...
  host: {
    '(document:storage)': 'onStorageChange($event)'
  }
})
export class MyComponent {
  onStorageChange(ev:KeyboardEvent) {
    // do something meaningful with it
    console.log(`Localstorage change/updated!`);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM