Patryk Ordon
Patryk Ordon

Reputation: 37

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?

Upvotes: 3

Views: 897

Answers (2)

Angela Amarapala
Angela Amarapala

Reputation: 1052

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

Upvotes: 3

shashi kumar
shashi kumar

Reputation: 382

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!`);
  }
}

Upvotes: 1

Related Questions