How to change toggle icon of mat-expansion-panel?

2 min read 06-10-2024
How to change toggle icon of mat-expansion-panel?


Customizing the Toggle Icon in Angular Material's mat-expansion-panel

Angular Material's mat-expansion-panel component provides a visually appealing and functional way to display expandable content sections. One common customization need is to change the default toggle icon that appears next to the panel header.

Let's explore how to achieve this with ease.

Scenario: You have a simple mat-expansion-panel component in your Angular application, and you want to replace the default arrow icon with a custom icon of your choosing.

Original Code:

<mat-expansion-panel>
  <mat-expansion-panel-header>
    <mat-panel-title> Panel Title </mat-panel-title>
  </mat-expansion-panel-header>
  <p>Content within the panel</p>
</mat-expansion-panel>

Customizing the Toggle Icon:

To replace the default icon, you'll leverage the matExpansionIndicator directive and a custom SVG icon. Follow these steps:

  1. Create a Custom SVG Icon: Design your desired icon and save it as an SVG file (e.g., my-icon.svg). You can use online tools like SVG-edit or design it in your preferred vector graphics editor.

  2. Include the SVG in your Project: Add the SVG file to your project's assets folder.

  3. Create a CSS Class: Define a CSS class that uses the custom SVG icon. This class will be applied to the matExpansionIndicator directive.

    .my-custom-icon {
      background-image: url('./assets/my-icon.svg');
      background-size: contain;
      background-repeat: no-repeat;
      width: 24px;
      height: 24px;
    }
    
  4. Apply the CSS Class: In your HTML template, add the matExpansionIndicator directive to the mat-expansion-panel-header and apply your custom CSS class to it.

    <mat-expansion-panel>
      <mat-expansion-panel-header>
        <mat-panel-title> Panel Title </mat-panel-title>
        <mat-expansion-indicator class="my-custom-icon"></mat-expansion-indicator>
      </mat-expansion-panel-header>
      <p>Content within the panel</p>
    </mat-expansion-panel>
    

Additional Tips:

  • Animation: You can add CSS transitions to the matExpansionIndicator to create a smoother animation for the icon as the panel expands and collapses.
  • Custom Icon Size: Adjust the width and height values in the CSS class to match your desired icon size.
  • Icon Placement: The matExpansionIndicator can be placed within the mat-expansion-panel-header element, allowing you to customize its position relative to the panel title.

Conclusion:

By following these simple steps, you can easily change the toggle icon in your Angular Material mat-expansion-panel to create a more personalized user experience. Feel free to experiment with different SVG icons and styling to achieve your desired look and feel.

Further Exploration: