4

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

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks for your reply, can you explain the top bit more? I'm guessing that's gonna be in js and "someValue" is the value I'm trying to get? The @hostListener I get declaration expected err and onJsValue name not found.
Yes, window.dispatchEvent() is JS. The other part needs to be inside a component. Please post the exact error message if that is not enough information.
Thanks for clearing the window.dispatchEvent(), I've posted the error in my original post. I put it in my constructor, not sure if that's the right place to put it basically just following this angular.io/docs/ts/latest/api/core/index/HostListener-var.html and thought it'd be similar.
Looks its working, doesn't work if the the button is in iframe.
Yeah thought it would, here's the example I meant to post yesterday. I've added the iframe as well to show it plnkr.co/edit/4urt9Y9nPBeQ0it9oMiv?p=preview
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.