Tips for ensuring the HTML checkbox element is fully loaded before programmatically selecting it

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.

Answer №1

To receive notifications when the checkboxes are dynamically added to the DOM using the *ngFor loop:

  1. Assign a template reference variable to each checkbox element (e.g. #chk)
  2. Link the checkbox elements to a QueryList using ViewChildren
  3. Subscribe to the changes in the QueryList observable within the ngAfterViewInit lifecycle hook and handle the list of checkboxes in the callback function. You can also perform a direct check in ngAfterViewInit to cover scenarios where the checkbox elements are already displayed
<input type="checkbox" #chk *ngFor="let id of idList" [id]="id">
@ViewChildren("chk") private checkboxList: QueryList<ElementRef<HTMLInputElement>>;

...

ngAfterViewInit() {
  // Verify if the checkbox is currently present in the DOM
  this.findCheckBoxWithId("chk36");            

  // Search for the checkbox if it appears after a delay
  this.checkboxList.changes.subscribe(() => {
    this.findCheckBoxWithId("chk36");          
  });
}

findCheckBoxWithId(id) {
  const checkbox = this.checkboxList.find(x => x.nativeElement.id === id);
  ...
}

Refer to this stackblitz for a live demonstration

Answer №2

Expanding on the solution provided in ConnorsFan's answer, an observable can be utilized:

@ViewChildren('chk') private checkboxQueryList: QueryList<ElementRef<HTMLInputElement>>;
checkbox$: Observable<HTMLInputElement>;

...

ngAfterViewInit(): void {
  this.checkbox$ = this.observableFromQueryListFind(
    this.checkboxQueryList,
    x => x.nativeElement.id === 'chk36',
  );
}

...

observableFromQueryListFind<T>(
  queryList: QueryList<T>,
  fn: (item: T, index: number, array: T[]) => boolean,
): Observable<T> {
  const item = queryList.find(fn);
  if (item) {
    return concat(
      of(item),
      queryList.changes
        .pipe(
          map((queryList: QueryList<T>) => queryList.find(fn)),
        ),
    );
  } else {
    return queryList.changes
      .pipe(
        map((queryList: QueryList<T>) => queryList.find(fn)),
      );
  }
}

This code snippet has not been tested, but is inspired by similar code that has proven to be successful around 80-90% of the time in a functioning codebase.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The essential guide to creating a top-notch design system with Material UI

Our company is currently focusing on developing our design system as a package that can be easily installed in multiple projects. While the process of building the package is successful, we are facing an issue once it is installed and something is imported ...

What could be the reason for my electron application consistently displaying false results when using Google Authenticator, despite entering the correct token?

Within this snippet of code, I am initiating a request to the main process to create a QR code using speakeasy and qrcode. document.addEventListener('DOMContentLoaded', async function() { const data = await ipcRenderer.invoke('generate-q ...

Guide to managing AutoComplete {onChange} in MUI version 5 with a personalized hook

Currently, I am utilizing a custom hook that manages the validation and handling of the onChange function. For most components like input, select, and textField, I have no trouble with handling the onChange event using the syntax below: The code snippet ...

Performing an AngularJS $http POST request with a combination of JSON parameter and query string

I'm currently trying to write an AJAX call using Angular's $http object in order to send a post request with JSON in the body and a query string appended to the URL. Despite going through the documentation for $http, looking for solutions on SO, ...

What is the best way to generate a JavaScript variable using information from SQLite?

I found the examples provided in the JavaScript edition of the Missing Manual series to be extremely helpful! OG.Q. I have explored various options but have not been able to find a solution to my problem yet. This is what I am trying to achieve: Save u ...

Sending information from Ajax to PHP

Could anyone please explain the script provided above to me? I am attempting to pass the value of $user data so that I can utilize $_REQUEST['user'] within sort.php, but I am encountering difficulties. It seems to be passing in a long URL. $(fun ...

Getting the text from an HTML input field requires accessing the value property of the

My goal is to generate a pdf report using php. The user will enter their name in an input box, which will then be passed to the second php page that searches the mysql database. Issue: When the user inputs their name, attempting to retrieve the data (var ...

Is there a way to immobilize an object in JavaScript without resorting to Object.freeze()?

Is there a way to freeze the following object without relying on Object.freeze()? Let's find out: const obj = { a:'test', b:'Something' } ...

There seems to be an issue in Angular as it is unable to retrieve /

I'm encountering an issue with my simple application where I am receiving the error message "Cannot GET /." Also, in the console, I see this error: TypeError: Cannot read property 'checked' of null at Object.SL_BBL_locer. I'm unsure ab ...

How to access a variable from outside a promise block in Angular

Is there a way to access a variable declared outside of a promise block within an Angular 6 component? Consider the following scenario: items: string[] = []; ngOnInit() { const url='SOME URL'; const promise = this.apiService.post(url ...

Initially, the OWL Carousel image is not displaying correctly due to incorrect sizing

I am currently working with OWL Carousel and have implemented a code that displays one image at a time, with the next image sliding in every 15 seconds. The width is set to occupy 100% of the screen and I have configured the JavaScript accordingly so that ...

SimpleModal Jquery experiencing intermittent flashing in Firefox

While utilizing the SimpleModal plugin for jQuery, I've encountered an unusual issue specific to Firefox (other browsers such as Chrome, Safari, Opera, and IE are working perfectly). The problem arises when I click on the button that triggers the mod ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Add a feature to a functional component that is enclosed with React.forwardRef

Within my codebase, there exists a component that is wrapped with React.forwardRef and serves as a compound component. One challenge I encountered was how to preserve the functionality of Form.Item = FormItem; while still having the Form component fun ...

Leveraging the Firebase email trigger extension with JavaScript

Recently, I integrated the email trigger extension for Firebase. Below is the function I am using: firestore .collection("profiledata") .doc(user.uid) .update({ accountStatus: "active", }) .then(() => { // At this p ...

The failure of a unit test involving Jest and try-catch

I am facing an issue with creating unit tests using jest. exportMyData.js const createJobTrasferSetArray = async () => { const data = exportData(); const jobTransferSet = []; try { data.forEach((element) => { const JobPathArray = el ...

Steps for implementing a datepicker in a dynamically generated element

Snippet of jQuery code that adds an element to a container $(container).append( '<label class="control-label col-md-3">Join Duration</label>' + '<div class="col-md-4">' + '<input type="text" name="join_dura ...

Tips for preloading a small placeholder image before the main content is loaded

After browsing , I noticed an interesting image loading style. The website initially shows a patterned image before revealing the actual content. This method creates visually appealing content while waiting for the entire webpage to load. Upon inspecting ...

Create logic statements based on the information obtained from parsing an XML document

Looking for some assistance with writing this code. Any help is appreciated! Let's say I am extracting data from an XML file like the following: function parseXml(xml) { $(xml).find("ITEM").each(function() { var foo = $("bar", this).text ...

Launching Angular 2 application on Heroku

Previously, I would combine my Angular 1 and Rails applications and deploy them on Heroku, which always went smoothly. However, now that I've transitioned to Angular 2, I'm looking to segregate my Angular and Rails code. I've successfully cr ...