Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

420
Views
How to click on an element that is in the body pragmatically from inside of an angular component?

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!