To collapse a div in an HTML Angular environment, the button must be clicked twice

A series of divs in my code are currently grouped together with expand and collapse functionality. It works well, except for the fact that I have to click a button twice in order to open another div. Initially, the first click only collapses the first div.

<div *ngFor="let item of data; let i = index">
      <button
        (click)="setIndex(i)"
      >
        <span
          [translate]=“item.title”
        ></span>

      </button>
      <div
        [class.collapse]='currentIndex !== i'
      >
        <div [innerHTML]=“item.description | translate"
        ></div>
      </div>
      <hr>

    </div>

In addition, the typescript function in question is as follows:

setIndex(i) {
    this.currentIndex = this.currentIndex === -1 ? i : -1;
  }

I attempted changing the click event to mousedown or keydown, but unfortunately, it did not yield the desired outcome.

Answer №1

To enhance the functionality of your setIndex function, modify it as shown below:

setIndex(i) {
   this.currentIndex = this.currentIndex === i ? -1 : i;
}

It is crucial to update the currentIndex value with the newly clicked index i in order to ensure that the corresponding div is displayed properly.

If the current div is already visible and you click on it again (meaning currentIndex === i), simply set it back to -1 to collapse it.

Answer №2

Revise your setIndex() as shown below.

Explanation

We initially set currentIndex = -1.

When a user clicks on any button, we need to check if currentIndex is -1 and then assign the value of i to currentIndex.

Now there are 2 more scenarios to consider. If a user keeps clicking on the same button repeatedly, we have to verify i === currentIndex

The last scenario is that when the first div is open with currentIndex = 0, and subsequently, if a user clicks on the third button leading to index = 2, we must first assign

currentIndex = -1 and then currentIndex = i

html

<div *ngFor="let item of data1; let i = index">
      <button (click)="setIndex(i)">
        <span>{{item.title}}</span>
      </button>
      <div [hidden]='currentIndex !== i'>
        <div>{{item.description}}</div>
    </div>
    <hr>
</div>

ts

setIndex(i) {
    if (this.currentIndex === -1) {
        this.currentIndex = i;
    } else if (this.currentIndex === i) {
        this.currentIndex = i;
    } else {
        this.currentIndex = -1;
        this.currentIndex = i;
    }
}

Note:

I have used [hidden] here just for demonstration purposes. You can customize it 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

Strategies for handling uncaught promise rejections within a Promise catch block

I'm facing a challenge with handling errors in Promise functions that use reject. I want to catch these errors in the catch block of the Promise.all() call, but it results in an "Unhandled promise rejection" error. function errorFunc() { return ne ...

Is it possible to generate an interactive HTML form using JSON information?

When the user clicks the "get Form" button, a request is sent to the form API to retrieve information for rendering the form. Once the form is rendered, the user can then submit the form. This process can be repeated as needed. HTML: <body ng-app="Json ...

Is the issue of res.locals not being properly propagated to all requests in Express middleware persisting?

Currently, I am building a web app using express, node, and handlebars with passport as the authentication library. In an attempt to customize the navigation bar based on the user's state, I am trying to set a variable in res.locals. However, I am enc ...

Error occurs when attempting to access window.google in Next.js due to a TypeError

I've been working on integrating the Google Sign In feature into my Next app. Here's how I approached it. In _document.js import React from 'react'; import Document, {Html, Head, Main, NextScript } from 'next/document'; expo ...

I'm a beginner in React Native and I'm attempting to display a "Hello World" text when the button is pressed. Unfortunately, the code below is not

''' import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react' const handlePress = () => { <View> <Text> Greetings universe ...

Create your masterpiece on a rotated canvas

My goal is to draw on a canvas using the mouse, even after rotating and scaling the canvas container. The issue I am facing is that the mouse coordinates get affected by the rotation and scaling, making it difficult to draw correctly. I have tried switch ...

The enigmatic loop traversal

Can you figure out why the name property of the merged object is properly set in the code below, even though the for-loop starts with i = 1? function merge(root){ for ( var i = 1; i < arguments.length; i++ ){ for ( var key in arguments[i] ){ ...

Encountering issues with React Nextjs - unable to utilize useState hook or

Hi everyone, I'm new to React and I think I might have overlooked something. I've been trying to create a simple registration form, but it seems like I'm having trouble changing the state. ` import {useState} from 'react' export ...

Leveraging the package.json file to execute a separate script within the package.json file

Within my project's package.json file, I have a script called npm run script1. Additionally, my project includes a private npm package as a dependency, which contains its own set of scripts in its package.json file, including one named script2. My goa ...

Create dual modules within a single project

I am working on a mean-stack project. In my index.js, at the end, I have: router.get('*', function(req, res) { res.sendfile('./views/index.html'); }) module.exports = router; Now, I need to handle all webpages that match https://l ...

Is there a solution to fix the issue with IE causing hover effects not to

I'm currently in the process of designing a website, and I have implemented some image hover effects that reveal elements within the image when you hover over it. These effects are functioning correctly on Chrome, Safari, and Firefox; however, they ar ...

Ways to switch Bootstrap 5 accordion element using JavaScript

I am using Bootstrap 5's accordion component and I would like to toggle this component from a custom JavaScript function called toggle, preferably without relying on jQuery. <!doctype html> <html lang="en"> <head> <meta ch ...

How come despite installing node 10.1.0, the system is showing the installed version as 5.6.0?

After I downloaded the NPM Windows installer from this link: https://nodejs.org/it/, I made sure to download and install the 10.1.0 version. However, when I checked my console using the command node -v, I was surprised by the following output: C:\U ...

Can you determine if the user is holding the CTRL key in a universally recognized way?

Can JQuery or Javascript detect if the user is holding the CTRL key outside of keyPress, keyUp events? Appreciate any insights. Thanks! ...

Issue encountered while trying to display images next to each other using only HTML and CSS

I am facing an issue with the vertical space between the top and bottom rows of my portfolio. There seems to be some unwanted space in the rows that I cannot account for. It doesn't seem to be a margin or padding within the box, so I suspect the probl ...

Discovering the method for accessing a variable within jQuery from a regular JavaScript function

As someone new to jQuery, I am currently facing a challenge with accessing a variable defined inside a jQuery block from a regular function. Despite my attempts, I have been unsuccessful in accessing it. Can anyone guide me on how to do this? <script l ...

Exploring the contents of JSON data using json-server

In my database file db.json, I have the following data: { "cases":{ "TotalCount":1, "StartingPageNumber":1, "Data":[ { "Id":1, "CaseNumber":& ...

What causes an image's size to change when it floats within the parent container?

There seems to be a height mismatch issue between the container and the image inside it when the parent is floated, but not the child. However, when both are given the float property, the height matches perfectly. Why is this? <div class="parent">&l ...

Updating JSON in JavaScript

I am striving to structure a JSON object in the following manner: {"tokenId":1,"uri":"ipfs://bafy...","minPrice":{"type":"BigNumber","hex":"0x1a"},"signature":"0 ...

Tips for efficiently showcasing array responses in Vue.js and Laravel

I am looking to showcase array data within a .vue file, but I am uncertain about the process. This is my attempt: <template> <div id="app"> <table class="table table-striped"> <thead> <tr> ...