0
votes

I have an expansion panel that contains a list of data. When the component loads, I want the panel to be expanded if the length of its data is 0, and collapsed if the length of its data is more than 0.

After initializing, I want the panel to only expand or collapse if the user clicks on it. So if the length of the panel's data changes from 0 to 1, I don't want the panel to then collapse, I want it to stay open. The problem is that when I use the expansion panel's [expanded] input, it keeps checking the condition, so when the length of the data changes it expands or collapses even if the user didn't click on it.

<mat-expansion-panel [expanded]="!item.data.length">
  <mat-expansion-panel-header>
    <mat-panel-title>
      Item with data
    </mat-panel-title>
  </mat-expansion-panel-header>
  <div *ngFor="let data of item.data">
    {{data.name}}
  </div>
  <button (click)="addDataToItem()">ADD DATA</button>
</mat-expansion-panel>

Desired results: The expansion panel is initially expanded if item.data.length is 0, and initially collapsed if item.data.length is more than 0. Then, if the user clicks the ADD DATA button, the expansion panel stays opened.

Actual results: The expansion panel is initially expanded if the item.data.length is 0, and collapsed if it is more than 0. But if the user clicks ADD DATA, the

panel closes because the length is more than 0.

Here is a an example of the behavior.

Notice how the panel is initially expanded because the length is 0, but then when you click ADD DATA, it collapses because the length is 1. I would like it to stay open.

2

2 Answers

2
votes

You can make a boolean in the Component and set it to item.data.length === 0 and just check that in the template.

public expanded: boolean = this.item.data.length === 0;

<mat-expansion-panel [expanded]="expanded">

edit: messed up the link

https://angular-esfqzh.stackblitz.io

0
votes

Try changing this:

<mat-expansion-panel [expanded]="!item.data.length">

to:

<mat-expansion-panel [expanded]="item.data.length">