Having issues with the Toggle Class feature in Angular 4. Looking to successfully add an active class upon clicking and display the content of the clicked list exclusively

I am currently utilizing [ngClass] to dynamically add the active class for displaying/hiding content upon click. While adding the class functions correctly, the issue arises when clicking, as it opens all other list items simultaneously. My desired outcome is to only display details of the specific list item that was clicked, without affecting others. How can I resolve this matter without resorting to using id or RefElement?

Thank you.

HTML

    <ul class="list-group panel-list-group list-group-inactive">
    <li class="list-group-item>
        <div class=" p-a-panel (click)="onShowDetails()">
        <div class="CollapseDetails" [class.active]="isOpen">
            <h3>Customer Details1</h3>
        </div>
        </div>
    </li>

    <li class="list-group-item>
        <div class=" p-a-panel (click)="onShowDetails()">
        <div class="CollapseDetails" [class.active]="isOpen">
            <h3>Customer Details2</h3>
        </div>
        </div>
    </li>
</ul>

TypeScript

     import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-admin-customer-central',
      templateUrl: './admin-customer-central.component.html',
      styleUrls: ['./admin-customer-central.component.css']
    })
    export class AdminCustomerCentralComponent implements OnInit {
      isOpen = false;
    
      ngOnInit() {
      }
    
      
      onShowDetails() {
        this.isOpen = !this.isOpen
    }
   }

CSS

    .CollapseDetails {
      display: none;
    }
    
    .active{
      display: block;
    }

Answer №1

The issue at hand is that all your panels are checking the same property to decide if they should be open.

An effective solution would involve creating a distinct model for each panel. For example:

export class CustomPanel {
  title: string;
  content: string;
  isOpen: boolean;
}

Then, in your view model, you can form an array of custom panel objects:

import { Component, OnInit } from '@angular/core';
import { CustomPanel } from 'src/models/custom-panel-model';

@Component({
  selector: 'app-dashboard',
  templateUrl: 'src/dashboard.component.html',
  styleUrls: ['src/dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  panels: Array<CustomPanel> = [
    { title: 'Panel Title 1', content: 'Panel Content 1', isOpen: false }
    { title: 'Panel Title 2', content: 'Panel Content 2', isOpen: false }
    { title: 'Panel Title 3', content: 'Panel Content 3', isOpen: false }
    ];

  ngOnInit() {

  }

  onTogglePanel(panel) {
    panel.isOpen = !panel.isOpen
  }
}

Finally, iterate through them in your view:

<ul class="panel-list">
  <li *ngFor="let panel of panels">
     <div class="panel-item" (click)="onTogglePanel(panel)">
        {{ panel.title }}
        <div class="panel-details" [class.active]="panel.isOpen">
            <p>{{ panel.content }}</p>
        </div>
      </div>
  </li>
</ul>

By maintaining the collapse state within each CustomPanel object, the panels can independently expand or collapse.

Feel free to check out this sample implementation here: https://example.com/sample

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

What is the process for displaying an object in HTML?

In my angular project, I have an array of product objects that I want to render. Currently, I am able to display it as a JSON object: <td>{{o.products |json}}</td> Here is an example output: [ { "id": 4, "name": & ...

The CORS policy is causing a blockage for the front-end application due to the Spring Boot backend

Currently working with Spring Boot and Angular. I have included the cross-origin annotation in my code to allow access from my Angular localhost port, but unfortunately, I am still encountering the following error: https://i.sstatic.net/4uDuv.png Here is ...

Is it possible to consolidate this type definition?

I generated the following code snippet: type NumberFields<T, K extends keyof T> = T[K] extends number ? K : never; type AnsFields<T> = SomeOtherList & NumberFields<T, keyof T>; In the code above, SomeOtherList consists of predefined ...

Oh no! I need assistance - I received a TypeError because I cannot read the property 'title' of undefined

I am currently working on an Angular project that is connected to a JAVA project. In this project, I needed to import a coupon from the database into a component in order to display it to the user. To achieve this, I created a specific function: import { ...

What data type should I specify for a function that outputs an instance of a class?

When I create a function that returns a class, the structure looks like this: function createClass() { return class implements ISomeInterface {/* ... */} } export { createClass } However, I am now encountering a warning from ESLint: Missing return type ...

"Looking to swap out the Angular theme's CSS stylesheet for your entire application? Here's

I was initially facing an issue while trying to import CSS through index.html as I kept getting a MIME type error: enter image description here The browser refused to apply the stylesheet from 'http://localhost:4200/css/pink-bluegrey.css' because ...

Utilizing JQuery Definitions for File Upload in Typescript

I'm currently working with TypeScript and facing an issue with a file upload form. However, when I try to access the files from the input element in my TypeScript code, an error is generated. $('body').on('change', '#upload_b ...

Displaying an array in HTML where one parameter serves as the key is a common task that

{ "Id": "12345", "length": [ { "review": { "1": { "request": [ { "days" ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

Even when imperfections inevitably arise, flawless submission is always achieved

When working with a form that has a set minimum and maximum number of characters, I encounter an issue. If the minimum is set to 2 characters and I only input one character, I receive a mat-error message. However, upon clicking save, it allows me to procee ...

How can I transform a string array into an object array using Angular 2?

If I have an array like this: categories = ['Fruit', 'Vegetable', 'Grain']; I want to transform it into an array of objects with the following structure: [ { id: 1, type: 'Fruit' }, { ...

NPM packages: Providing a comprehensive assets and images delivery solution package

After creating a custom (angular2) npm package and uploading it to my personal registry, I encountered an issue with delivering the icons along with the component. The component should display an icon by using the following template: <span [class]="& ...

Assign the chosen value to the dropdown list if ngModel is present

I currently have a select field implemented in my Angular component: <select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)"> <option class="form-con ...

In what way does TypeScript assign an object's type based on its current value?

let object = { key1: 123, key2: 'abc' } If we analyze, the data type of object is: { key1: number, key2: string } However, there are times when I wish its datatype could be defined as: { key1: 123, key2: 'abc' } Moreover, consideri ...

In what scenarios is it appropriate to utilize ES6 format to develop a component in React TypeScript without relying on props?

What is the preferred way to write a component that does not pass props in React? Should it be like const xxxx = (yyyy) (from es6?) or const xxxx: FC = () => {yyy}? In my example, I believe using FC for CompA is more appropriate because it uses props f ...

How can I use "Lite-Server" with NPM start to showcase my index.cshtml file on the browser?

Currently, I am trying to navigate the world of Visual Studio Code and figure out how to run/compile my project. Starting a new project in Visual Studio was simple enough, but now that I'm working with Visual Studio Code, I find myself struggling to s ...

Placing images inside a div causes them to vanish

I encountered a strange issue where the images I added to a background disappeared. .Background1{ position:relative; top:0%; left:0%; height:100%; width:100%; content:url("/assets/backgroundlayer1.jpg") } .Background2{ posi ...

Angular Material 2 Progress Indicator Cover

Looking to implement a Progress Bar overlay during processing? I have the ability to calculate percentage complete and want to utilize a determinate progress bar for this task. Instead of a Spinner, I aim to use a dialog similar to what is demonstrated in ...

Refreshing a page while preserving the same URL

Looking for a way to reload the page at the same URL in Angular, I came across a solution that seems to work: this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => { this.router.navigate(['Your actual ...

Is it possible to merge these two scripts into a single one within Vue?

As a newcomer to VUE, I am faced with the task of modifying some existing code. Here is my dilemma: Within a single component, there are two script tags present. One of them contains an import for useStore from the vuex library. The other script tag incl ...