Angular Material Collapse Panels: Allowing initial expansion followed by user-controlled expand/collapse functionality

My goal is to have an expansion panel that contains a list of data. Upon loading, I want the panel to be expanded if there is no data, and collapsed if there is data present.

Once initialized, I only want the panel to expand or collapse when the user interacts with it by clicking on it. If the amount of data changes from 0 to 1, I do not want the panel to automatically collapse; it should remain open. The issue arises when using the expansion panel's [expanded] input, as it continuously checks the condition and collapses or expands based on any change in data length, even if the user did not click on it.

<mat-expansion-panel [expanded]="!item.data.length">
  <mat-expansion-panel-header>
    <mat-panel-title>
      Item with data
    </mat-panel-title>
  </mat-expansion-panel-header>
  <div *ngFor="let data of item.data">
    {{data.name}}
  </div>
  <button (click)="addDataToItem()">ADD DATA</button>
</mat-expansion-panel>

Desired Scenario: Initially, the expansion panel will be expanded if item.data.length is 0, and collapsed if it is greater than 0. Subsequently, upon clicking the ADD DATA button, the expansion panel should remain open regardless of the data length.

Current Outcome: At first, the expansion panel is expanded if the item.data.length is 0, and collapsed if it is greater than 0. However, upon clicking ADD DATA, the panel closes due to the increase in data length.

You can view an example demonstrating this behavior here.

Observe how the panel initially expands because the length is 0, but collapses when you add data by clicking ADD DATA since the length becomes 1. My intention is for it to stay open in such situations.

Answer №1

To simplify, create a boolean variable in the Component and set it to check if item.data has a length of zero, then use this boolean in the template for easy verification.

public isItemEmpty: boolean = this.item.data.length === 0;

<mat-expansion-panel [expanded]="isItemEmpty">

Correction: link provided was incorrect.

Answer №2

Consider modifying the following:

<mat-expansion-panel [expanded]="!item.data.length">

to:

<mat-expansion-panel [expanded]="item.data.length">

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

"Sorry, there was an issue with AmStockCharts when trying to update the chart: Unable to assign a value to the '

Currently, I am using Angular 4.3.6 along with TypeScript 2.4.2 for my project. The issue that I am facing involves reading data from a socket and attempting to add it to the dataprovider. I came across an example at: While implementing a serial chart, q ...

Distinguishing Literal and Parameterized Routes in Angular 6

I've encountered a strange issue that I'm not sure how to handle. In my application, you can either view your public account or create a new one. The Account and CreateAccount modules are standalone and lazy loaded in the routes.ts file. export ...

retrieveStyle() rooted framework Category

I have implemented a customized Native Base style theme following the instructions in this link. Imports: import material from './native-base-theme/variables/material'; import getTheme from './native-base-theme/components'; return ( ...

The module "<file path>/react-redux" does not contain an exported member named "Dispatch"

Currently, I am in the process of following a TypeScript-React-Starter tutorial and have encountered an issue while wrapping a component into a container named Hello.tsx. Specifically, at line 4, the code snippet is as follows: import {connect, Dispatch} ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

Web Development Woes: AngularJS and Angular-Material Failing to Render HTML Even with Object in $scope

I have been searching extensively for a solution to this issue without any luck. Any assistance in this matter would be highly appreciated. Key Details: Using angular-material tabs When an item is selected from a dropdown, a request is sent to a firebas ...

Angular 2 - Inconsistent Data Persistency in Service

Reviewing the following code snippet, it can be seen that the CartService class contains a Cart class. The addToCart() function is used to store CartItem(s) in the cart and then display them in the console to demonstrate the functionality. xxxxxxxxxxxxxxx ...

State hook variable not being properly updated within a functional component

After updating the name of an ingredient, I am looking to save this data as an ingredient with the new name: from "Milk" to "Cow's milk". I've included simple steps (1,2,3) in comments to outline the process briefly, but for clarification, assum ...

The Meteor Call object stands apart from the Meteor Method object that was received

When I send an object from the client to the server using a Meteor Call and Meteor method, something strange happens. The object is received in the Method but it looks different - nested within the giftList. Meteor Call - JSON.stringify {"personName& ...

Validation errors in the realm of Zod

Below is my code using Next.js 14 with TypeScript, React Hook Form, and Zod for validation. The issue arises when trying to display an error message for an empty form: import React from "react"; import category from "@/components/expenses/ca ...

What exactly is the meaning of "Dispatch<SetStateAction<boolean>>" in React with TypeScript?

I am currently working on writing Frontend Tests for React Components in TypeScript. The code I am using belongs to a more seasoned programmer, so some of the data types are unfamiliar to me. One particular prop has been defined with the data type "Dispa ...

There is an issue with the navigation keys not functioning correctly within the cellrenderer input boxes in ag grid

Struggling with an autocomplete input box within the cell renderer component in an ag grid cell. When attempting to use the left/right navigation keys, the input does not move inside the box and instead exits the cell abruptly. Similarly, navigating down ...

Converting a stringified array object to an object using Expressjs

When working with Angular, I am sending stringified data using FormData. Here is an example: this.formData.append('data', JSON.stringify(this.collections)) Now my challenge is converting this string back to an object in my Express backend. The d ...

Does adding a callback to object.ngOnDestroy() replace its internal onDestroy() method?

I'm enhancing the drag and drop feature in Angular <div cdkDropList appImprovedDropList> <div cdkDrag>item 1</div> <div cdkDrag>item 2</div> <div cdkDrag>item 3</div> </div> The directive appImpro ...

Experimenting with the static method within a singleton class using Typescript and Sinon

I have a separate layer in my application that uses a DAO class to retrieve data from the repository. I've implemented the DAO class as a Singleton and made its methods static. In another class, I've created service methods to manipulate the dat ...

"In the combined declaration of 'DepartmentListComponent', all individual declarations must either be exported or kept local." - error message regarding routing components in TypeScript file

I followed a video tutorial to write this code, but it's not working as expected and is throwing some errors. Is it possible that the tutorial is outdated and using an older methodology? The code seems to be hard-coded without using any services. Her ...

Leverage Redux in Angular for account balance management

As I work on creating an app in Angular where users can make purchases and have the price deducted from their account balance, I've been delving into Redux. The scenario involves individual user accounts with independent balances and no interaction be ...

Error TS2339: The property 'SOLDE' is not found in the 'AdvTitres' type

I am working with an array and need to retrieve the value of the SOLDE variable. You can find the JSON file here. When I try to access the SOLDE property, I get the following error message: error TS2339: Property 'SOLDE' does not exist on type ...

Disabling Array elements based on a condition in Angular 5

I am managing a list of participants: <div class="heroWrapper"> <div class="image hero" *ngFor="let participant of participants; index as i" [class]="i === selectedParticipant ? 'selected hero' : 'image hero'"> ...

The Angular URL functions perfectly on localhost:4200, but encounters issues in the build project

After developing my project locally, the sub URLs like http://localhost:4200/login work fine. But once I build the project using ng build --prod, all sub URLs stop functioning on the live server. When I navigate to a sub URL using this.router.navigate([&a ...