I am using Angular web components in a static html page. I am able to inject data into Angular component. But when I try to retrieve data from Angular component to the HTML page, it is not working. I am not sure what I am doing wrong here.
The code is as below:
component ts code
@Output() myOutput:EventEmitter<string>= new EventEmitter();
outputMessage:string="I am child component."
sendValues() {
this.myOutput.emit(this.outputMessage);
}
component html code
<button (click)="sendValues"> Send Data </button>
JS code in static html
var commCompTag = document.getElementsByTagName('comm-comp');
if(commCompTag.length > 0){
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>');
commCompTag[0].addEventListener('myoutput', (event) => {
var evtDetails = event;
console.log('evtDetails >>> ', evtDetails);
console.log(event.detail);
});
// commCompTag[0].addEventListener('myoutput', function(event) {
// var evtDetails1 = event;
// console.log('evtDetails1 >>> ', evtDetails1);
// console.log(event.originalEvent.detail);
// });
}
I have tried the above solution by referring to Angular Elements EventEmmitter : $event not showing emitted value but it didn't help me out. So it will be great if someone can give me some pointers to resolve this issue.
Because the index.html is technically not part of the bootstrapped angular app, you may need to resort to non Angular-specific solutions.
One approach/POC may be to do the following.
Get a reference to my-app
element via constructor
constructor(private elRef: ElementRef) {}
construct and dispatch an event on the nativeElement
sendValues() {
console.log('sending values');
this.myOutput.emit(this.outputMessage);
const event = new CustomEvent('my-app-data', {
detail: {
value: {
message: this.outputMessage
}
}
});
this.elRef.nativeElement.dispatchEvent(event);
}
Register to listen for that event in index.html
jsonCommCompTag[0].addEventListener('my-app-data', function(event) {
var evtDetails1 = event;
console.log('evtDetails1 >>> ', evtDetails1.detail.value.message);
});
don't forget invocation in your button click event handler in app.component.html
(click)="sendValues()"
STACKBLITZ
https://stackblitz.com/edit/angular-ivy-zbj7ru?file=src/index.html