I have created an Angular Web Component like below
@Component({
selector: 'dlx-comp',
templateUrl: './comp.component.html',
styleUrls: ['./comp.component.scss'],
encapsulation: ViewEncapsulation.Native,
})
export class CompComponent implements OnInit {
onClick() {
console.log('alert click');
}
}
and template is very simple
<button (click)="onClick()"></button>
and in my app module
export class AppModule {
constructor(private injector: Injector) {
}
ngDoBootstrap() {
this.defineElement(compComponent, 'dlx-comp');
}
private defineElement(component: any, elementName: string) {
const el = createCustomElement(component, { injector: this.injector });
customElements.define(elementName, el);
}
}
everything is working fine and I have embedded it in a simple HTML page like below
<head>
<meta charset="utf-8">
<title>TMIBot</title>
<base href="/">
<meta name="viewport" content="height=device-height, width=device-width, initial-scale=1.0, user-scalable=no">
<title>Test Angular Elements</title>
<link rel="stylesheet" href="https://urltomy/dist/dlx-styles-1.0.css">
</head>
<body>
<button id="button">Open comp </button>
<dlx-comp id="comp"></dlx-comp>
<script type="text/javascript" src="https://urltomy/dist/dlx-chatbot-1.0.js"></script>
<script>
const button = document.querySelector('#button');
button.addEventListener('click', () => {
const comp = document.querySelector('#comp');
comp.click();
});
</script>
</body>
</html>
Now I want to call the click
method on it. but it doesn't do anything, no errors in console, also I checked comp
has value;
That's because you are defining (click)
on button
inside dlx-comp
, and you are trying to fire click
event on dlx-comp
you should find that button inside dlx-comp
and on it fire click
button.addEventListener('click', () => {
const comp = document.querySelector('#comp');
const btn = comp.querySelector('dlx-comp::shadow button');
btn.click();
});