Show additional information when the button is clicked

I am encountering an issue with my Angular Material expansion panel. I want to automatically expand the accordion if there are validation errors when a button is clicked. However, the problem arises when the user manually minimizes the accordion by clicking on the minimize arrow. In this case, even though the expanded property is already true, the accordion does not expand again.

Below is the code I am using:

Wrapper component

Mat accordion HTML

<mat-accordion>
    <mat-expansion-panel (opened)="data.panelOpenState === true" (closed)="data.panelOpenState === false" [expanded]="data.expanded">
        <mat-expansion-panel-header (click)="stateValue()">
            <mat-panel-title>
                {{ data?.title }}
            </mat-panel-title>
        </mat-expansion-panel-header>
        <ng-content></ng-content>
    </mat-expansion-panel>
</mat-accordion>

Mat accordion TS

import { Component, Input, OnInit } from '@angular/core';
import { SidePanelAccordianData } from './side-panel-accordian.model';

@Component({
  selector: 'app-side-panel-accordian',
  templateUrl: './side-panel-accordian.component.html',
  styleUrls: ['./side-panel-accordian.component.scss']
})
export class SidePanelAccordianComponent implements OnInit {
  @Input() data: SidePanelAccordianData;

  constructor() { }

  ngOnInit(): void {
  }

  stateValue() {
    this.data.panelOpenState = !this.data.panelOpenState;
  }

}

Mat accordion model

export class SidePanelAccordianData {
  public title: string = '';
  public panelOpenState: boolean;
  public expanded: boolean;


  constructor(args) {
    this.title = args.title;
    this.panelOpenState = args.panelOpenState;
    this.expanded = args.expanded;
  }
}

component html where I am using the accordion

<app-side-panel-accordian [data]="{title:'Title', panelOpenState: true, expanded: secondDriverExpanded}">
    <div class="inner-row-data">
      <form-input [formStatus]="formStatus" [parentFormGroup]="setupForm" [data]="{
        formControlName: 'secondDriverName',
        name: 'secondDriverName',
      }" (onBlur)="setSecondDriverDetails('name')">
      </form-input>
    </div>
</app-side-panel-accordian>


<form-button type="button" (click)="onNext()">Next</form-button>

component ts where I am using the accordion

public secondDriverExpanded = true;

onNext() {
 <!--if there are validation errors-->
 this.secondDriverExpanded = true;
}

Currently, if a user clicks on the minimize arrow in the UI to collapse the accordion, the expanded property remains true. How can I ensure that it is set to false when the accordion is minimized so that it can be re-expanded correctly on the next button click?

https://i.sstatic.net/gFy0O.png

Answer №1

The Angular Material Expansion Panel is an extension of the CdkAccordionItem component, which introduces two output properties: closed and opened. These properties emit events when the panel is closed or opened, allowing you to monitor its current state.

Here is an example of how to use it:

<mat-expansion-panel (opened)="panelOpenState = true" (closed)="panelOpenState = false">
</mat-expansion-panel>
public panelOpenState = false;

If you have a wrapper around your expansion panel, you may need to define a custom output to handle event propagation. For instance:

@Component({
  template: '<mat-expansion-panel (opened)="expansionStateChange.emit(true)" 
                            (closed)="expansionStateChange.emit(false)" ...'
})
class YourWrapper {
@Output expansionStateChange = new EventEmitter<boolean>();
}

You can then use the expansionStateChange output to update the secondDriverExpanded property as needed.

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

Tips for correctly passing the appropriate data type using generics in TypeScript

If I have an array of objects with a key called render, which may be an optional function that takes a parameter (unknown type) const objectArray = [{a: 1}, {b: 2, render: renderFunction}, {c: 3, render: anotherFunction}] suppose the second object's ...

Utilizing custom i18n blocks for Vue 3 and Vuetify 3 to enhance locale messages

Looking to localize messages separately for each component? Check out this example for Vue 2. But how can it be done for Vue 3 and Vuetify 3? Here's what I've tried: package.json "dependencies": { "@mdi/font": "6.5 ...

Error Message: The specified HTML element already contains two instances of the WebViewer, leading to a conflict in PDFTron React TypeScript Next

Having some trouble using pdftron with my docx editor. I can use the editor fine, but keep encountering an error like the one shown below: https://i.stack.imgur.com/OnJxE.png https://i.stack.imgur.com/l9Oxt.png Here is a snippet of my code: wordeditor.t ...

Encountering an error message stating "Cannot access 'color' property of undefined" while setting up HighCharts in my xx.ts file

I am new to incorporating highcharts into my project and struggling with it. Despite following documentation and trying various methods, I have not been able to make it work as intended. My multi-series high charts were functioning properly until I decide ...

The theming feature in Angular 5 with Bootstrap 4 and Bootswatch seems to be malfunctioning

Having trouble implementing bootswatch themes with angular 5 and bootstrap 4? I've added the following to styles.scss: @import "~bootswatch/dist/cerulean/variables"; @import "~bootstrap/scss/bootstrap"; @import "~bootswatch/dist/cerulean/ ...

Ionic: Fixed button located at the bottom of a specific ion-slide

I've been creating a series of slides with questions, and the final slide serves as a summary of the previously answered questions. I want to ensure that the submit button is always visible at the bottom of this last slide. However, I've encounte ...

Encapsulate the module function and modify its output

I am currently utilizing the node-i18n-iso-countries package and I need to customize the getNames function in order to accommodate a new country name that I wish to include. At the moment, I am achieving this by using an if-else statement like so: let cou ...

Issue detected in Angular 2 Heroes Tutorial: The element with the selector "my-app" was not found in the document

Currently, I am in the process of following along with the Heroes tutorial on the official angular website. The project was created using CLI and everything seemed to be working smoothly up until Part 6 on Routing: https://angular.io/tutorial/toh-pt5 In ...

Tips for incorporating Google Docs into a web application to enable previewing, editing, and saving functionality

Incorporating Google Docs into a web application (Angular 10) for previewing, editing, and saving is my goal. I have documents stored on my server and would like to utilize Google Docs to preview these files, whether they are stored on Amazon S3, Azure, o ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

Relocating to new pages as WebSocket connection terminates and then reconnects

Currently working on a React project with Vite, encountering an issue where the websocket connection closes and re-establishes when navigating to another page using the sidebar. Main.tsx :- import ReactDOM from 'react-dom/client'; import App fro ...

Guide to Generating Toggle Buttons with For Loops in Angular 4/6

In my latest project, I have successfully implemented a demo with three buttons dynamically generated using a for loop on the backend response. Each button is clickable and toggles between active and inactive states upon click. However, I am seeking advic ...

How do I configure an Angular project in Nx Workspace to be served as HTTPS?

Currently, I have an nx workspace set up with an Angular project and a NestJS backend. Everything is compiling and functioning properly. Now, the need has arisen to locally host the Angular app using https for development purposes. Typically, I would use t ...

Refreshing a textarea manually in Typescript

My textarea has the CSS property height: auto;. However, I noticed that when I reset the variable associated with the [ngModel] of this textarea (e.g. using this.myNgModelVar = "";), the height of the textarea doesn't automatically decrease unless the ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Typescript: The original type cannot be indexed with a type-mapped type

I'm currently working on a class where I need to define a method that returns an object with keys based on the generic type inferred by the compiler. However, I've encountered an issue with the code snippet below. The compiler is indicating that ...

Convert information into an Observable

I have a scenario where I am fetching a list of items from an Observable in my Angular service. Each item contains an array of subjects, and for each subject, I need to make a separate API call to retrieve its details such as name, description, etc. Data ...

Ported an Angular application to Android with the help of Cordova. The APK successfully launches on the emulator, however, when tested on a physical device, only a blank

Struggling to convert my angular app with Cordova to an android app. The APK file works on the emulator, but when installed on a real device, it only shows a white blank screen, never loading. Seeking assistance as I am new to Cordova and Android developme ...

Challenge Encountered with Create-React-App TypeScript Template: Generating JS Files Instead of TSX Files

Encountering a problem setting up a new React application with TypeScript using the Create-React-App template. Followed the guidelines on the official documentation (https://create-react-app.dev/docs/adding-typescript/) and ran the command below: npx creat ...