Monday 13 January 2020

'Click' function not working within typescript/angular after finding element using 'document.querySelector'

I have an element on a page in my Angular 8 Project.

This element has an attribute of 'data-convo-id' with a unique string attached to it.

On this element is a click function that will load data based off of the data attribute that is also on that element (as described above).

Because I won't strictly have access to this element, I need a way of finding the element on this page using 'document.querySelector()', and then triggering a click on it. This in turn will fire off the function attached to that element, which will load the data as requested.

I've tried two different methods of doing this and both don't work. See below.

Method 1:

// This gets the ID that we're looking for from the NgRx Store.
const currentID = this.State$.currentId;

// This finds the element on the page with the data attribute, plus the ID from above.
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;

// Simulate click on that element.
relevantElem.click();

Method 2:

// Create the event
let event = document.createEvent("HTMLEvents");

// Tie the event to 'click'
event.initEvent("click", true, true);

// This gets the ID that we're looking for from the NgRx Store.
const currentID = this.State$.currentId;

// This finds the element on the page with the data attribute, plus the ID from above.
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;

// Simulate click event on that element.
relevantElem.dispatchEvent(event);

For reference, here is the HTML element itself:

<p #el [attr.data-convo-id]="conversation.id" (click)="viewConversation(el)"><strong>VIEW</strong></p>

In summary, both click events do nothing. Even if I add a 'SetTimeout' function along with a console log to ensure it is clicked after a decent amount of time, and the click is still ignored.

I get zero errors with the above code.



from 'Click' function not working within typescript/angular after finding element using 'document.querySelector'

No comments:

Post a Comment