Angular Typescript @ViewChildren getting undefined error

45 views Asked by At

I have a mat-table that contains an entity called Groups. These groups are retrieved from a data source and it will have more than 50 rows. However, it seems the data table only retrieve the first 14 rows based the the height of the table until the user starts to scroll down. I also have an array of checkboxes on the same data table but the values will be dynamically displayed, and I use @viewchildren retrieve the value of checkboxes (true/false).

 @ViewChildren('groupCheckboxes') viewGroupCheckboxes: QueryList<CheckboxComponent>;

.....

Here is a scenario. Assuming I have agency A to Z, and A, B, Y are stored in the data source so when the values are first loaded, I need to show the checkbox next to A, B and Y are checked.

  //In this use case, Groups A to Z have already been loaded at this point, the setupGroupCheckboxes() method will traverse the data table and find A, B and Y.  It will set the checkboxes next to A, B and Y to true.
  setupGroupCheckboxes(): void {
    for (const refItem of this.preSelectedGroups){
      let matchingIndex = this.rowsGroups.findIndex(item => item.id === refItem.id);
      if (matchingIndex !== -1) {
        this.viewGroupCheckboxes.get(matchingIndex).checked = true;
        this.groupCheckboxArray[matchingIndex] = true;
        this.isGroupLoaded = true;
      } else {
        this.isGroupLoaded = false;
      }
    }
  }

The problem is after the form is loaded initially, the checkboxes beyond 14 is not accessible at this point, so in this example, the index for Y is 24, I will get the undefined error because though the Group data is already in the array (I can see it in debug mode), checkboxes (index 15 to 25) for those Groups are not in the user's view yet, and I will get the undefined error.

ERROR TypeError: Cannot set properties of undefined (setting 'checked').

I have done some research and experiments and it doesn't seem the data table has a limit on how many rows it can load initially, it might be controlled by the height of the table (if I shrink the height of the table, it loads fewer than 14 rows initially). The current height of the data table is the maximum I can set. So I am wondering if anyone has any idea to get around this problem. Thanks!

1

There are 1 answers

0
Mike On

Well, it appears that the mat-table API I adopted set the [virtualScroll]="true" by default. After I set it to false, the problem is resolved.