简体   繁体   中英

Closing Angular Mat-Expansion Panel on Click

I have seen a few requests for toggling opened and closed Angular Material, but I am looking to always close it on the button click. So if the panel is opened and the button is clicked, then close the panel.

Toggle works without any problem, but when I try to always close it (by setting the panelOpenState to false, it isn't seeming to work for me.

In my html I have:

<mat-expansion-panel [expanded]="panelOpenState">
    <mat-expansion-panel-header>
      <mat-panel-title>
        Workouts
      </mat-panel-title>
    </mat-expansion-panel-header>
   <a href="#">Create Workout</a>
  </mat-expansion-panel>

  <div>
    <div (click)="closePanel()">
      <h2>Training Plans </h2>
    </div>
  </div>

What I am trying to acheive is closing the panel when the div is clicked. To do this, my click event in the ts file is as shown below:

...
export class SidenavComponent {
  panelOpenState: boolean = false;

  closePanel() {
    this.panelOpenState = false;
  }
}

On top of this, I have tried a few different methods within the closePanel() function. The only method that has successfully worked is the toggle ( this.panelOpenState = !this.panelOpenState ).

How can I always close the panel? Setting it to false on click does not appear to work. The idea for me clicking on the div and having it close is because I want the panel to close any time I go to a different route.

We can solve this by using two-way binding on the expanded attribute of mat-expansion-panel.

<mat-expansion-panel [(expanded)]="panelOpenState">
    <mat-expansion-panel-header>
    ...
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM