The issue with collapsible elements not functioning properly in an Angular application involving CSS and JS

My implementation of collapsible in a plain HTML page looks like this:

<!DOCTYPE html>
<html>
<head>
  <title></title>

<style>
button.accordion {
    background-color: #777;
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
}

button.accordion.active, button.accordion:hover {
    background-color: #555;
}

button.accordion:after {
    content: '\002B';
    color: white;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: '';
    background-image: url('download.jpg');
    display: inline-block;
    background-size: 30px 30px;
    width:30px;
    height:30px;
    transform:rotate(180deg);
}

div.panel {
    padding: 0 18px;
    background-color: #f1f1f1;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}


* {
  box-sizing: border-box;
}


#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
a{
     text-decoration: none;
     color:white;
}
</style>

</head>
<body>
<h2>Collapsible</h2>
<p>Click the button to toggle between showing and hiding the collapsible content.</p>




<div id="div2">
<button class="accordion"><a href="#">Addq</a></button>
<div class="panel"> 
  <p>Some collapsible content. Click the button to toggle between showing and hiding the collapsible content. Lorem ipsum dolor sit amet,ome Some collapsible content. Click the button to toggle between showing and hiding the collapsible content. </p>
<button class="accordion"><a href="#">Aollapsible</a></button>
<div class="panel">
  <p>sdfsdfsdfsdt amet,ome Some collapsible content. Click the button to toggle between showing and hiding the collapsible content. </p>
</div>
<button class="accordion"><a href="#" style="">Dollapsible</a></button>
<div class="panel">
  <p>qqqqqqqqqqqpsible content. consequat.</p>
</div>
<button class="accordion"><a href="#">Qollapsible</a></button>
<div class="panel">
  <p>zzzzzzzzzllapsible content. commodo consequat.</p>
</div>

</div>

<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}


</script>


</body>
</html>

JS Fiddle: https://jsfiddle.net/c2r70eh6/4/

However, when I tried implementing the same code in an Angular application, the collapsible section didn't expand as expected. When working with Angular, I placed the HTML code in the component's HTML file, the CSS in the component's CSS file, and copied the JS into the index.html file.

The collapsible feature works fine in a simple HTML file but not in Angular. I have verified all the IDs and they are correct.

I would appreciate your assistance. Thank you in advance!

Answer №1

I don't necessarily agree with your current approach, but in order to achieve the desired outcome, here are the necessary changes you need to make in the Component Class:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  acc = document.getElementsByClassName("accordion");

  ngOnInit() {
    for (let i = 0; i < this.acc.length; i++) {
      (<HTMLButtonElement>this.acc[i]).onclick = function () {
        this.classList.toggle("active");
        var panel = <HTMLDivElement>this.nextElementSibling;
        if (panel.style.maxHeight) {
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        }
      }
    }
  }

}

Check out this Live Example on StackBlitz for reference.

Answer №2

The collapsing of panels can be achieved using pure CSS without the need for angular.

To collapse the panels, simply toggle the active class on button click and utilize the direct sibling combinator to style the next div as open or shut:

.panel {
    padding: 0 18px;
    background-color: #f1f1f1;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}

.accordion.active + .panel {
    max-height: 500px;
    transition: max-height 0.2s ease-out;
}

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
  }
}
button.accordion {
    background-color: #777;
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
}

button.accordion.active, button.accordion:hover {
    background-color: #555;
}

button.accordion:after {
    content: '\002B';
    color: white;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: '';
    background-image: url('download.jpg');
    display: inline-block;
    background-size: 30px 30px;
    width:30px;
    height:30px;
    transform:rotate(180deg);
}

.panel {
    padding: 0 18px;
    background-color: #f1f1f1;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}

.accordion.active + .panel {
    max-height: 500px;
    transition: max-height 0.2s ease-out;
}

* {
  box-sizing: border-box;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

a{
     text-decoration: none;
     color:white;
}
<h2>Collapsible</h2>
<p>Click the button to toggle the collapsible content.</p>;

<div id="div2">
<button class="accordion"><a href="#">Addq</a></button>
<div class="panel"> 
  <p>Some collapsible content. Click the button to toggle between showing and hiding the collapsible content. Lorem ipsum dolor sit amet,</p>
<button class="accordion"><a href="#">Aollapsible</a></button>
<div class="panel">
  <p>sdfsdfsdfsdt amet,</p>
</div>
<button class="accordion"><a href="#" style="">Dollapsible</a></button>
<div class="panel">
  <p>qqqqqqqqqqqpsible content.</p>
</div>
<button class="accordion"><a href="#">Qollapsible</a></button>
<div class="panel">
  <p>zzzzzzzzzllapsible content.</p>
</div>

</div>

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

Passing a particular method of a specific instance as an argument

I am interested in creating a class that allows me to specify "For instance a1 of A, you will call the function computeValue() of a specific instance b1 of B when the value is needed". It's important for me to indicate which method of which instance w ...

Guide on Deleting Specific Item Using SQL Data Source Delete Statement

I am facing an issue when trying to remove a specific item from a grid view in my SQL server database. I have configured DataKeyNames and linked a sql data source with the grid view. The delete command is set as follows: DeleteCommand="DELETE FROM product ...

Stopping React from re-rendering a component when only a specific part of the state changes

Is there a way to prevent unnecessary re-renders in React when only part of the state changes? The issue I'm facing is that whenever I hover over a marker, a popup opens or closes, causing all markers to re-render even though 'myState' rema ...

Utilizing Vue.js: Dynamically Rendering Components Based on Routes

I needed to hide some components for specific Routes, and I was able to achieve this by using a watcher for route changes that I found in this StackOverflow question - Vuejs: Event on route change. My goal was to not display the header and sidebar on the c ...

Customizing Ngx-bootstrap Carousel Indicator, Previous, and Next Button Styles

<carousel > <a href=""> <slide *ngFor="let slide of slides"> <img src="{{slide.imgUrl}}" alt="" style="display: block; width: 100%;"> </slide> 1. Is there a way to substitute the indicators with images ...

Creating a Next.js application that retrieves mock data and dynamically presents it on the user interface

I've been attempting to retrieve some placeholder data from an API and showcase it on the screen, but unfortunately nothing is appearing. Interestingly, the data does show up in the console, just not on the actual screen. function Shop() { const [pr ...

Include a selection of images within a popover box

I am currently working on a component that contains various experiences, each with its own popover. My goal is to display an array of images within each popover. Specifically, I have different arrays of images named gastronomiaExperience, deportesExperien ...

Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images. Solving the Issue ...

using javascript to retrieve php variables

After creating a webpage, setting up Apache2 on an Ubuntu server to access it over the internet, and installing PHP5 and MySQL, I encountered issues with accessing database information on my page through a .php file. Despite having a file named test.php th ...

Having trouble sending form data using the jQuery AJAX POST method?

I am facing an issue with a simple form that is supposed to send data to PHP via AJAX. However, when I submit the form, the data does not get sent across. Here is the JavaScript code: $(document).ready(function(e) { $('#update').submit(func ...

Sanitize input data prior to using express-validator in a Node.js application

In my Node.js project, I am utilizing the V4 syntax of express-validator as recommended: const { check, validationResult } = require('express-validator/check'); const { matchedData } = require('express-validator/filter'); Additionally ...

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

Steps for retrieving a table of records with Jquery and sending it to the server through AJAX

Displayed below is a table I have: <table cellspacing="0" rules="all" border="1" id="ContentPlaceHolder1_GridView1" style="border-collapse:collapse;" class="table table-striped"> <tbody> <tr> <th scope="col"> ...

Address NPM vulnerabilities through manual fixes

I downloaded a repository and ran an npm install, but encountered an error at the end. Now, every time I run npm audit, I receive the following message: found 18 vulnerabilities (5 low, 12 moderate, 1 high) in 15548 scanned packages 9 vulnerabilities requ ...

Capturing the dynamic server response with nested JSON structures

I am in the process of creating a dynamic data-binding function named assemble that requires two input parameters: server response (JSON) - nested JSON object. instruction set (JSON) - a configuration object that dictates the binding. The Issue: The cur ...

Cassandra encountered a TypeError stating that the "value" argument is exceeding the bounds

I keep encountering the error message below. Any thoughts on what might be causing it? TypeError: "value" argument is out of bounds at checkInt (buffer.js:1041:11) at Buffer.writeInt32BE (buffer.js:1244:5) at Encoder.encodeInt (/ ...

Learn the technique of invoking a sub component's method from the parent component in Vue.js

I am looking to trigger a method in a sub component from the parent component in Vue.js in order to refresh certain parts of the sub component. Below is an example showcasing what I aim to achieve. Home.vue <template> <componentp></compo ...

Next.js Page is failing to render React component props

I am currently facing an issue where I need to display data from the props object in a functional component using React. The component structure looks like this: interface TagsComponentProps { tags: Tag[]; } const TagsComponent: FC<TagsComponentPro ...

The AJAX callback resulted in the request being aborted and the window location being

I am currently working on implementing a client-side redirect for users who are deemed invalid. The server checks if the user has access to the current page, and if not, it returns {data: 'invalid'}. In the success callback of the ajax call, I va ...

Exploring ViewChild Usage in Angular 8's Inheritance

I've encountered an issue with inheritance and ViewChild in a class where I always seem to get undefined. Let me simplify the problem for better understanding. First, let's look at the parent class: @Component({ selector: 'parent', ...