In my Angular 8 Project, there is an element on a page with a unique string attached to the attribute 'data-convo-id'.
This element has a click function that loads data based on the data attribute specified above. However, without direct access to this element, I need a way to locate it using 'document.querySelector()' and trigger a click event on it to execute the associated function.
I've attempted two different methods to achieve this, both of which have been unsuccessful. See below for details:
Method 1:
// Get the ID from the NgRx Store
const currentID = this.State$.currentId;
// Find the element on the page with the required data attribute and ID
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;
// Simulate a click on the element
relevantElem.click();
Method 2:
// Create a new HTML event
let event = document.createEvent("HTMLEvents");
// Initialize the event as a 'click'
event.initEvent("click", true, true);
// Retrieve the desired ID from the NgRx Store
const currentID = this.State$.currentId;
// Locate the element with the necessary data attribute and ID
const relevantElem: HTMLElement = document.querySelector(`[data-convo-id=${currentID}]`) as HTMLElement;
// Dispatch the click event on the element
relevantElem.dispatchEvent(event);
Here is the HTML representation of the element:
<p #el [attr.data-convo-id]="conversation.id" (click)="viewConversation(el)"><strong>VIEW</strong></p>
Unfortunately, in both cases mentioned above, the click events fail to trigger any action. Even after implementing a 'setTimeout' function with console logs to ensure adequate time delay, the clicks do not register.
There are no errors reported with the provided code snippets.