Search code examples
cssangularangular-materialmat-expansion-panel

How to toggle mat expansion panel based on screen width?


I have an expansion panel which needs to be closed on certain media devices. For e.g. If the web app is in mobile I want to contract the expansion panel and if it in desktop I want to expand it. How can I achieve this requirement?

This is mat expansion panel I used

<mat-accordion class="example-headers-align">
                <mat-expansion-panel>
                  <mat-expansion-panel-header>
                    <mat-panel-title>
                      Description
                    </mat-panel-title>
                  </mat-expansion-panel-header>
                  <p class="">
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Amet mauris commodo quis imperdiet massa tincidunt. Viverra nibh cras pulvinar mattis nunc sed blandit. Sollicitudin tempor id eu nisl nunc mi ipsum faucibus. Lectus vestibulum mattis ullamcorper velit sed ullamcorper. Consectetur lorem donec massa sapien faucibus. In est ante in nibh. Ullamcorper malesuada proin libero nunc consequat interdum varius. Curabitur vitae nunc sed velit. Mauris a diam maecenas sed enim ut sem viverra.        
                  </p>
                </mat-expansion-panel>
              </mat-accordion> 

I research that can do this by using @media attribute in css.

@media only screen and (max-width: 600px) {
  */contract expansion panel*/
}

Help would be appreciated. Thanks in advance.


Solution

  • In your .ts file, you can access the window width. You can do it using one of the following properties:

    const width  = window.innerWidth || document.documentElement.clientWidth || 
    document.body.clientWidth;
    

    Then you can simply toggle your mat-expansion-panel programatically based on the returned number.

    You should be able to use one of the answers to this question for the expansion: How to toggle Angular material expansion panel programmatically