I have worked with Angular Material for several years and I love how easy it is to integrate their components into my apps. Among some of the most popular components like MatTab and MatTable, I often use MatExpansionPanel to render data that regulates a parent-child relationship. The problem with MatExpansionPanel is that it will automatically close when the data is getting updated. For example, assume we have a list of parent folders which also contain several sub folders that need to be loaded at runtime. The issue occurs right after sub folder data is loaded. Since the data structure has changed MatExpansionPanel suddenly collapses and the user needs to expand the panel again to view the contents. The issue is demonstrated below:

Image for post

Expansion Panel automatically closes when data get updated

My First Attempt

Initially I thought this can be easily fixed by adding some custom logic to reopen the panel after the data is getting loaded. By doing this the parent folder can finally expand after sub folders are rendered but I am not fully satisfied with the current behavior. As the result, the expansion panel starts collapsing for a few milliseconds then begins to open again which, in fact, is not very graceful to see.

Image for post

Ungraceful Success

After some time struggling to find the root cause, I realized that the problem is not caused by MatExpansionPanel itself. It’s definitely a side effect of the way my data structure gets updated.

In my implementation I use *ngFor structural directives to render each expansion panel. When the data structure is updated, *ngFor destroys existing MatExpansionPanels and re-renders the components again which causes all the states of the expansion panel to be lost completely. I then started digging into Angular doc to understand how *ngFor works and found out something interesting that might help me fix this problem.

#angular-material #javascript #ui #angular #design

How I Fix Strange Behavior of MatExpansionPanel
8.70 GEEK