Home > Software design >  How to click on an element that is in the body pragmatically from inside of an angular component?
How to click on an element that is in the body pragmatically from inside of an angular component?

Time:12-16

I have a website on which I have crisp chat service running and I'm trying to click on the chat box from one of my component's typescript files.

The crisp chat box is a div with the id of crisp-client inside body tag. How do I click on it from inside my typescript?

CodePudding user response:

Inject Renderer2 in constructor -

constructor(private renderer: Renderer2) {}

Get the crisp-client element in your component -

let crispClient = this.renderer.selectRootElement('#crisp-client');

Perform click() event -

crispClient.click();

Working demo here

Added a test method on div to check -

<div id="crisp-client" onClick="console.log('crisp client clicked')"></div>

CodePudding user response:

You can use the ViewChild decorator and pass a template reference variable as a string, and manipulate the event. Here's a simple example of clicking Button 1, which programmatically clicks Button 2 and due to that click, the text of Button 2 is changed:

<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

You can access elements of body using document object in Angular. This way, you can achieve the click of the element which is inside body. Here's one more example where I am clicking the button which is inside 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>

Here's a Stackblitz demo.

  • Related