Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable from vanilla JS to Angular2

I'm trying to get an object title from a vanilla javascript and retrieve it on my angular 2 component. At the moment I'm saving the variable to localStorage however I don't think that's a good way of doing it.

To save the variable to localStorage is being set when button is clicked, button is in iframe.

Can someone point me to the right direction how to achieve this?

Edit re the answer below: Rest of the red bit are "Cannot find name" enter image description here

like image 912
nCore Avatar asked Mar 11 '23 06:03

nCore


1 Answers

You can emit an event and listen to it in Angular

window.dispatchEvent(new CustomEvent('js-value', { bubbles: true, detail: 'someValue' });

and then listen in Angular

export class MyComponent {
  constructor() {}

  @HostListener('window:js-value', ['$event.detail'])
  onJsValue(val) {
    console.log(val);
  }
}

This way you also won't have issues with change detection because Angular runs change detection by itself when an event handler is called.

like image 80
Günter Zöchbauer Avatar answered Mar 20 '23 13:03

Günter Zöchbauer