5
votes

I am trying to display multiple Mat-expansion-panel within a Mat-accordian by using *ngFor. I need to add a new mat-expansion-panel on click of a button which i am able to do. I am also required to expand (open) this newly added expansion panel on click of the button, and this is what i have been unable to achieve. Please help.

Stackblitz - https://stackblitz.com/edit/angular-fh5vu1-g6phe6?file=app%2Fexpansion-steps-example.ts

export class ExpansionStepsExample { 
  items: number[] = [1,2,3];

  AddNewRow() {
    this.items.push(4);
  }
}
<mat-accordion class="example-headers-align">
  <mat-expansion-panel *ngFor="let item of items;">
    <mat-expansion-panel-header>
      <mat-panel-title> {{item}} </mat-panel-title>
    </mat-expansion-panel-header>
    {{item}}
  </mat-expansion-panel>
</mat-accordion>
<button (click)="AddNewRow()" value="Add New"> Add New </button>
3

3 Answers

5
votes

You can access the Material Expansion Panel element, and call the methods open() and close().

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatExpansionPanel } from '@angular/material';
...
@ViewChild(MatExpansionPanel, {static: true}) matExpansionPanelElement: MatExpansionPanel;
...
selectItem() {
    this.matExpansionPanelElement.close(); //open()
}
<mat-accordion>
    <mat-expansion-panel #matExpansionPanel>
    ...
    </mat-expansion-panel>
</mat-accordion>
2
votes

I recommend changing you data model. in this way you can store the state of the open and close plus the number per item.

item = [
  {
    number: 1, 
    open: false
  },
  {
    number: 2,
    open: true
  }
];

  AddNewRow() {
     this.item.push({number: 3, open: true});
   }
<mat-accordion class="example-headers-align" multi="true">
   <mat-expansion-panel *ngFor="let item of items;" [expanded]="item.open" >
      <mat-expansion-panel-header>
         <mat-panel-title> {{item. number}} </mat-panel-title>
      </mat-expansion-panel-header>
         {{item.number }}
   </mat-expansion-panel>
</mat-accordion>
<button (click)="AddNewRow()" value="Add New"> Add New </button>
0
votes

A small change to the answer by @sem for Angular 9+ use: component.ts

@ViewChild('matExpansionPanel', { static: true }) matExpansionPanelElement: MatExpansionPanel;

component.html

<mat-expansion-panel #matExpansionPanel>