Ashane Alvis
Ashane Alvis

Reputation: 810

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.

Upvotes: 0

Views: 2248

Answers (2)

Pardeep Jain
Pardeep Jain

Reputation: 86800

For such scenarios, you can use Media Queries from controller side not from the CSS file.

I mean to say store the value of screen width (media query using JS) in some variable and depending on the value of variable toggle your accordian.

in mat-expansion-panel there is attribute binding using expanded

           <mat-accordion class="beagel-headers-align">
            <mat-expansion-panel [expanded]="isMobileWidth">
              <mat-expansion-panel-header>
                <mat-panel-title>
                  Description
                </mat-panel-title>
              </mat-expansion-panel-header>
              <p class="">
                Lorem ipsum.....
              </p>
            </mat-expansion-panel>
          </mat-accordion> 


          isMobileWidth = true // check here using media query in .ts file

Upvotes: 1

mike
mike

Reputation: 1863

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

Upvotes: 1

Related Questions