简体   繁体   中英

Angular mat-checkbox checked not equal to form group

While creating a dynamic list of mat-checkbox components (Angular Material 8.2.3) I noticed some weird behaviour regarding change detection. The mat-checkbox does not seem to change according to its form control correctly.

Use case: A user should be able to select multiple options based on some external data. Some options are required in which case the form should display those as both checked and disabled.

Reproduction: Stackblitz

Selecting a minimal value from the select should filter the checkboxes based on their value. The value of 60 is always required. The checkboxes show the expected behaviour the first time a number is selected but start showing weird behaviour after changing the selection a few times. The required and disabled checkbox is no longer checked and sometimes a different checkbox is checked while it shouldn't. The form control state (printed below the checkboxes) seems to be correct.

A workaround that I found was to manually trigger change detection after removing all options. Using the existing form controls with setValue instead of creating new form controls does not make a difference.

What is the cause of this behaviour and is there a better way to resolve it than to (manually) force an additional change detection cycle?

You can do a different approach. Instead of changing the form array you can change the number of options that are shown to the user depending on the minimum value.

See here: Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM