When a user accesses the page, I want certain checkboxes to be automatically checked. To achieve this, I am storing the IDs of the HTML checkbox elements in a service. Upon entering the page, the service is utilized to retrieve an array containing these IDs. The active elements are then checked using a loop.
this.platform.ready().then(() => {
let checboxState = this.service.checboxState;
if (checboxState !== undefined && checboxState.length > 0) {
checboxState.forEach(checbox => {
let element = document.getElementById(checbox.id) as HTMLInputElement;
element.checked = true;
});
}
});
However, I encountered the following error:
Uncaught (in promise): TypeError: Cannot set property 'checked' of null
This error might indicate that the JavaScript function is being triggered before the DOM has fully loaded. Despite using platform.ready()
, it does not seem to ensure that the DOM is ready for manipulation. I have attempted other methods such as:
-
document.addEventListener("DOMContentLoaded",() => {})
- window.onload = () => {}
but none were successful in resolving the issue.
I eventually got the function working by adding a setTimeout()
before its execution. How can I properly wait for the HTML elements to load before running the JavaScript function?
The checkboxes on the page are generated using an *ngFor directive.