I am trying to call an Angular function from within JS, however the parameters being passed to Angular are undefined. What am I missing? Ideally I would like to return a result from a dispatchedEvent as well. Is there a better solution I should be using?
JS function
var event = new CustomEvent('test', {
id: "a", id2:"ttt"
});
window.dispatchEvent(event);
Angular component
@HostListener('window:test', ['$event.id','$event.id2'])
test(id,id2) {
console.log('ang called from JS: '+id+' '+id2)
}
Output to console: ang called from JS: undefined undefined
GOAL: ang called from JS: a ttt
As far as I know, you can only pass one parameter to CustomEvent
, which is detail
. So, your code should not be compilable. You need to change it as
onClick() {
const event = new CustomEvent('test', {
detail: {
id: 'a', id2: 'ttt'
}
});
window.dispatchEvent(event);
}
After this, your handler will be
@HostListener('window:test', ['$event.detail.id', '$event.detail.id2'])
test(id, id2) {
console.log('ang called from JS: ' + id + ' ' + id2);
}