Generate a distinct variable name within the *ngFor loop

I am trying to create a dynamic table where clicking a button displays the row directly beneath it.

I checked out a helpful post on this topic, but didn't find the exact solution I needed.

The current setup works but reveals all hidden rows because they share the same collapse variable.

Below is a working example, though not entirely correct:

<table>
<thead>
  <th>Path out of this queue</th>
  <th *ngFor="let role of roles">{{role.RoleName}}</th>>
</thead>
<tbody>
  <ng-container *ngFor="let queue of workQueues; let i = index">
    <tr>
      <td><button (click)="collapse=!collapse">{{queue.WorkQueueName}}</button></td>
      <td *ngFor="let role of roles">
        <input type="checkbox" />
      </td>
    </tr>
    <tr *ngIf="collapse">
      Yay...
    </tr>
  </ng-container>
</tbody>

I attempted to make the collapse variable unique by appending the i (index) to it, resulting in the following error:

Parser Error: Got interpolation ({{}}) where expression was expected

My solution:

<table>
<thead>
  <th>Path out of this queue</th>
  <th *ngFor="let role of roles">{{role.RoleName}}</th>>
</thead>
<tbody>
  <ng-container *ngFor="let queue of workQueues; let i = index">
    <tr>
      <td><button (click)="{{collapse+i}}={{!collapse+i}}">{{queue.WorkQueueName}}</button></td>
      <td *ngFor="let role of roles">
        <input type="checkbox" />
      </td>
    </tr>
    <tr *ngIf="{{collapse+i}}">
      Yay...
    </tr>
  </ng-container>
</tbody>

How can I create a unique variable in the (click) event that I can utilize?

Answer №1

(click)="this[collapse+i] = !this[collapse+i]"

By using an indexer, you can easily access the field on the component. The functionality, however, relies on how the collapse fields are defined in your component.


I personally suggest adding an extra field to the type contained in the workQueues array.

(click)="queue.collapsed = !queue.collapsed"

...

<tr *ngIf="queue.collapsed">

Another option is to define a new field within the *ngFor loop.

<ng-container *ngFor="let queue of workQueues; let i = index; let isCollapsed = true">
<tr>
  <td><button (click)="isCollapsed = !isCollapsed">{{queue.WorkQueueName}}</button></td>
  <td *ngFor="let role of roles">
    <input type="checkbox" />
  </td>
</tr>
<tr *ngIf="!isCollapsed">
  Yay...
</tr>
</ng-container>

Check out the example on StackBlitz

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

Transforming a simple MySQL query into a structured nested JSON format

Is there a way to easily reorganize data without using complex for loops (perhaps with Underscore.js or refining the MySQL query)? I have data formatted like this: [ { "J_NUM": "BOAK-1212", "X_DUE_DATE": "2012-06-20T00:00:00.000Z", "X_LEAD_T ...

Why does FormGroup.Get() return null when there is a period in the name of the FormControl?

Issue: I am facing an issue with the formGroup I created using formbuilder. The problem arises when a control within the FormGroup contains a . in its name. When attempting to retrieve the formControl using the formGroup.get method, it returns null. Sampl ...

Skrollr's transformation effect makes the text tremble

Using skrollr.js, I am implementing transition effects on an inner div nested inside another div. The inner div is positioned relatively. Here are my codes: HTML Structure <div class="outer"> <div class="inner-div" style="transition:transform ...

What causes the error of inputRef.current being null in CurrencyTextField?

When attempting to target the second 'CurrentTextField' after changing the value of the first 'CurrentTextField', an error occurs stating 'inputRef.current is null'. import React, {useRef } from 'react'; import Curr ...

The error message "There is no defined window.matchMedia prefers-color-scheme window in Next.js"

I am currently working on a project with React.js alongside Next.js and encountered an issue that I need assistance with. Upon loading the page, I need to set a variable that indicates whether the user is using dark mode or not. I attempted the following ...

What could be causing Jest to prevent me from using the node testing environment, especially when they have made changes to it?

I am currently working on testing a React component within Next.js using Jest. Jest made an official announcement regarding the change of default test environment to Node: Due to this update, the default test environment has been switched from "jsd ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

Retrieving data from an AJAX call and populating a knockout.js observableArray()

This phenomenon confuses me. There must be some small detail that I am missing here. My goal is to load a simple observableArray in knockout using an ajax call. javascript // We initialize the array with an empty array. var data = []; var viewModel = ...

Ways to display pictures by invoking an API within the antd item list container

Upon page load, I am fetching images from a database using an API. Now, my goal is to display these images within a Modal in Antd. How can I accomplish this with the code snippet below? const MyVehiclePage = (props) => { useEffect(() => { co ...

Tips for sending multiple values in a data object using jQuery AJAX

I am currently working on a form that contains two input fields, with the possibility of more being added later. The first input is a text field and the second is a checkbox. I want to be able to send these inputs using $.ajax. To accomplish this, I have ...

How can I use jQuery to automatically redirect to a different HTML page after updating a dynamic label?

When I click on a button in first.html, a function is called to update labels in second.html. However, despite being able to see second.html, I am unable to see the updated values in the labels. Can someone please advise me on how to achieve this? functi ...

Filtering with case sensitivity customization

I've successfully implemented a custom pipe to filter my data from the database. Here is the code for the pipe: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implements ...

Exploring the Versatility of Axios

Today, I implemented an AJAX request using Axios in JavaScript to submit form data. While the requests are being sent successfully, it seems that the backend is not able to receive the username and password information from the frontend. What could be ca ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

Understanding ReactJs component syntax: Exploring the nuances and distinctions

Currently diving into the world of Reactjs and working on creating a basic component. I'm puzzled about why this particular syntax for a component: import React, { Component } from 'react'; export default class AboutPage extends Component { ...

Retrieve the parent's current state by accessing it through a callback function in React

My callback function onRestore is only logging the history until the id of the clicked snapshot. Why is it showing incorrect state? I've exhausted all options, so any help would be appreciated. import React, { useState, useEffect, useRef } from "re ...

Difficulty encountered when combining create-react-app with typescript and immutable.js

After realizing that create-react-app now supports typescript, I encountered some issues while trying to transfer my current codebase from react-scripts-ts. Most of my classes are based on Record and cannot be constructed anymore due to errors like: Cannot ...

Display content based on selected option

I am struggling to display a div based on the selection I make. Unfortunately, it's not working as expected. Can anyone offer guidance on how to tackle this issue? <div class ="row"> <div class="form-group col-md-6"> <label for= ...

The nested click event is not functioning as expected

Below is a simplified version of HTML code containing 2 nested click events (one on the href and one on an input). When the user clicks on the input field, it inadvertently triggers the javascript function SelectTable() linked to the href event. This unint ...

Which is causing the block: the event loop or the CPU?

example: exports.products = (req, res) => { let el = 1; for (let i = 0; i < 100000000000000; i++) { el += i; } console.log(el); ... ... ... res.redirect('/'); }; If I include a loop like this in my code, which resour ...