How to prevent mat-expansion-panel from closing?

10.4k Views Asked by At

I have matAccordion in my page in which the number of panels are dynamic. Each of these panels contain a form. I want to prevent the closing of my panel until the form is duly filled and is valid.

I am not able to find any event that will prevent the panel from closing. The "(closed)" event fires after the panel close animation has happened.

Is there some logic to control the close?

4

There are 4 best solutions below

1
Nosheep On
  <mat-expansion-panel [expanded]="!formSubmited$ | async"></mat-expansion-panel>
5
kuklyy On

Simple solution there

your-component.html

...
<mat-expansion-panel [opened]="panelOpened($event)">
    <mat-expansion-panel-header [ngClass]="(isPanelOpened)?'no-events':'default'">...</mat-expansion-panel-header>
</mat-expansion-panel>
...

your-component.ts

...
isPanelOpened: boolean = false;
...
panelOpened(event) {
    this.isPanelOpened = true;
}

submitForm() {
    // submit form stuff
    ...
    // at the end
    this.isPanelOpened = false;
}
...

your-component.css

.no-events {
    pointer-events: none;
}

.default {
    pointer-events: auto;
}

On first panel open it will change isPanelOpened to true what removes event trigger on your mat-panel. That means user can not close it unlin the form is submitted. At the end of the submitForm() your are switching isPanelOpened to false what allows user to close the panel.

0
Ollie On

Add a class to your CSS, which has a rule that disables pointer events:

.disabled-pointer {
  pointer-events: none;
}

Then add this class conditionally to your mat-expansion-panel-header, e.g.:

<mat-expansion-panel-header [class]="formIsValid ? 'disabled-pointer' : ''">
    <mat-panel-title>Panel title</mat-panel-title>
</mat-expansion-panel-header>

To hide the toggle icon from the header, add the hideToggle prop conditionally to your mat-accordion, e.g.:

<mat-accordion [hideToggle]="formIsValid ? true : false">
    ...
</mat-accordion>
0
shekhar chander On

You can add an click event to the element (probably mat-expansion-panel-header) and stopPropagation for that.

Here's the code:

<mat-expansion-panel hideToggle (click)="$event.stopPropagation();">