Restrict toggling of MatExpansionPanel in Angular Material to only be triggered by clicking on the arrow icon

Utilizing Angular Material for my expanding panels, I am facing an issue with the toggling functionality. I would like the panel to expand and contract only when clicking on the arrow, not anywhere in the header area where I plan to place a checkbox. Currently, clicking on the checkbox triggers the toggling event of the panel before the 'change' event of the checkbox is executed.

I want to prevent the toggle action from firing when clicking on any part of the header except the arrow. How can I achieve this?

HTML

<mat-expansion-panel #panel
       (opened)="togglePanel()"
       (closed)="togglePanel()">
    <mat-expansion-panel-header>
        <mat-panel-title>
            <mat-checkbox (change)="onCheckChanged($event)">
                <label>Options 1</label>
            </mat-checkbox>
        </mat-panel-title>
        <mat-panel-description></mat-panel-description>
    </mat-expansion-panel-header>
</mat-expansion-panel>

TypeScript

togglePanel() {
    // this event fires before the onCheckChanged event
}

onCheckChanged(event: MatCheckboxChange) {
    // this event fires after the togglePanel event
}

Answer №1

There has been a feature request pending for about a year now, so it's uncertain when it will be implemented. There are some workarounds being tried out by users, but the reviews seem to be mixed.

https://github.com/angular/material2/issues/8190


Update:

I experimented with this code in stackblitz and it appears to be effective.

HTML:

<mat-accordion>
  <mat-expansion-panel #expansionPanel>
    <mat-expansion-panel-header (click)="expandPanel(expansionPanel, $event)">

Component:

 expandPanel(matExpansionPanel, event): void {
        event.stopPropagation(); // Preventing event bubbling

        if (!this._isExpansionIndicator(event.target)) {
          matExpansionPanel.close(); // This is where the magic happens
        }
      }

   private _isExpansionIndicator(target: EventTarget): boolean {
    const expansionIndicatorClass = 'mat-expansion-indicator';

    return (target['classList'] && target['classList'].contains(expansionIndicatorClass) );
  }

View on Stackblitz:

https://stackblitz.com/edit/angular-5kugm3?embed=1&file=app/expansion-overview-example.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I go about setting up $broadcast?

I've been utilizing the fantastic ngStorage plugin for Angular development. Setting up involves connecting a $scope-node to the localstorage in this manner: $scope.$store = $localStorage; The $scope.$store is now accessible across all controllers. ...

Outputting the square root of integers ranging from 4 to 9999

I'm looking to calculate the square root of all numbers up to 9999. Are there any ways to instruct the program to skip numbers that do not have a perfect square root? Below is the current code I am using: let i=1; for (i===1;i>=1 && i <10000;i ...

The specified format of `x-access-token` does not match the required type `AxiosRequestHeaders | undefined`

I am encountering an issue while trying to add an authHeader to the "Service". The error message displayed is: Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequest ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

Named Graph's Title on Image Save in Echarts

Is there a way to give a title to the image graph saved in Echarts, as Echarts does not have this option available? Any suggestions on how we can achieve this? Here is a link for reference from Echarts that provides the 'saveAsImage' option: Ch ...

Steps for displaying the appended string on a web page using React hooks

Check out this code snippet: const Gauge = (props) => { const points = 100; const radius = 257; const max = 100; const peaks = [ 10, 50, 90 ]; const step = (max + 1) / points; const realPeaks = peaks.map((peak) => Math.floor(p ...

Having trouble making md-data-table directives function properly

I'm struggling to incorporate the md-data-table library from https://github.com/daniel-nagy/md-data-table into my webpage. Despite loading the library in Chrome, none of the directives seem to be working. Here's a snippet of my code - can anyone ...

The 'formGroup' property cannot be bound as it is not recognized as a valid property of 'form' in Angular 7

I tried implementing a login feature using web API with Angular 7, but encountered an error when using <form [formGroup]="loginForm" (submit)="loginFormSubmit()">. What could be causing this issue? https://i.sstatic.net/3M2a5.jpg login.component.ht ...

The variable is accessed before it is initialized in the context of Next.js and Server Actions

Currently, I am utilizing the new Data Fetching feature in Next JS to retrieve data from an API and store it in a variable named 'contact.' However, I am facing the issue of receiving an error message stating that "variable 'contact' is ...

Transferring client-side data through server functions in Next.js version 14

I am working on a sample Next.js application that includes a form for submitting usernames to the server using server actions. In addition to the username, I also need to send the timestamp of the form submission. To achieve this, I set up a hidden input f ...

Developing an npm module encapsulating API contracts for seamless integration with front-end applications using Typescript

I am curious if Typescript supports this specific idea, and I could use some advice on how to make it work. In my project, there's a frontend application and a backend REST API with clear contract classes for Inputs and Outputs. These classes outline ...

What happens when i18next's fallbackLng takes precedence over changeLanguage?

I am currently developing a Node.js app with support for multi-language functionality based on the URL query string. I have implemented the i18next module in my project. Below is a snippet from my main index.ts file: ... import i18next from 'i18next& ...

Use the ng-pattern regex to specifically identify instances where a pattern occurs only once

Looking for a string pattern 'abcd' followed by a colon(:) and any number of integers, with the restriction that this pattern cannot be repeated. Here are some examples of valid patterns: - abcd:23415 - abcd:23 And invalid patterns: - asda:4 ...

Which is Better in AngularJS: Controller Constructor or Linking Function? Or, Is a Linking Function Really Necessary?

Is there a key component to consider when creating a new directive in regards to the link function? Typically, directives have a controller class defined which can be injected with $scope and $element. This allows all watchers and click handlers to be plac ...

Limiting the assignment of type solely based on its own type, without considering the components of the type

I have defined two distinct types: type FooId = string type BarId = string These types are used to indicate the specific type of string expected in various scenarios. Despite TypeScript's flexibility, it is still possible to perform these assignment ...

Resolve ESLint errors in _document.tsx file of next.js caused by Document<any> and ctx.renderPage = () with TypeScript usage

maxbause took the initiative to create a comprehensive boilerplate project for Next.js, complete with GraphQL and styled components in TypeScript. Check out the project here However, upon integrating ESLint into the project, I encountered several warning ...

Navigating between applications

Does anyone have suggestions on setting up routing between different apps without disrupting existing code? We want to make the integration process easy when adding a new app to our main application. For example, navigating from an electronics(main app) ...

Excessive use of the style attribute within an AngularJS directive

My AngularJS directive includes the replace: true and template: <span style="color: red;"></span> properties. However, when I use this directive in my code, it appears that the style attribute is duplicated in the rendered HTML: <span style= ...

Unable to specify d3 axis to exclusively display whole numbers

After reviewing a few answers on this, I found that they are not solving my issue. how-to-limit-d3-svg-axis-to-integer-labels d3-tick-marks-on-integers-only My problem centers around an array of years: years: Array<number> = [2010, 2011, 2012, 20 ...

Struggling to clear items from input field within AngularJS

I'm currently facing an issue where I am unable to delete data from an input field. var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', function MyCtrl($scope) { $scope.items = [ { name: & ...