If you want to manipulate events in Angular, you can make use of the ViewChild decorator by passing a template reference variable as a string. Here's an example where clicking Button 1
will programmatically click Button 2
, resulting in a change in the text displayed on Button 2
:
<button #button1 (click)="clickButton2()">
Click to change the text of Button 2
</button>
<button #button2 (click)="changeText()">{{ buttonText }}</button>
buttonText = 'Button 2';
@ViewChild('button2') button2: ElementRef<HTMLElement>;
clickButton2() {
let el: HTMLElement = this.button2.nativeElement;
el.click();
}
changeText() {
this.buttonText="Changed!"
}
Here's a Stackblitz demo
UPDATE
In Angular, you have the ability to access elements within the body using the document
object. This allows you to trigger events on elements inside the body
. Here's another example where I am simulating a click on a button that is located within the body
from a component:
<button (click)="handleClick()">Programatically click the button inside body</button>
ngOnInit() {
let btn = document.getElementById('main');
btn.addEventListener('click', (e: Event) => btn.innerHTML = "Clicked!");
}
handleClick() {
document.getElementById('main').click();
}
index.html
<html>
<body>
<my-app>loading</my-app>
<button id="main">Click</button>
</body>
</html>
Check out the Stackblitz demo for more details.