Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically expand a mat-expansion-panel, which was added dynamically?

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>
like image 946
adarsh Avatar asked Jun 10 '19 20:06

adarsh


2 Answers

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>
like image 182
Sem Avatar answered Sep 22 '22 12:09

Sem


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>
like image 40
Robert Leeuwerink Avatar answered Sep 21 '22 12:09

Robert Leeuwerink