Utilizing *ngIf within a loop to alternate the visibility of table rows with a designated class upon clicking on rows with a different class in Angular 2

I have created a table that displays data, and within this table there are 2 tr elements with the classes default and toggle-row. When I click on a tr element with the class default, it should only toggle the corresponding tr element with the class toggle-row. However, my current code toggles all the toggle-row elements when any default row is clicked. How can I fix this issue? I am using *ngIF to handle the toggling of table rows.

The template file looks like this:

<table class="table table-container table-responsive" id = "team-members">
        <thead class="table-heading">
            <tr>
            </tr>
        </thead>
        <tbody class="data-item" *ngFor = "let member of teamMember; let i = index" >
            <tr id ="{{i}}" (click)="Toggle(i)" class="default">
                <td *ngFor = "let hrs of member.Value.hoursLogged">
                    {{ hrs }}
                </td>
            </tr>
            <ng-container *ngFor = "let subtask of member.Value.subTasks">
                <tr class="toggle-row" *ngIf="toggle" > 
                        <td>
                            {{ subtask.taskType }}
                        </td>
                        <td *ngFor="let hrs of subtask.subtaskHoursLogged">
                            {{ hrs }}
                        </td>
                </tr>
            </ng-container>
        <tbody>
</table>

This loop creates the following structure:

 <table>
        <thead></thead>
        <tbody>
            <tr id="1" class="default"><tr>
            <tr class="toggle-row"></tr>
            <tr class="toggle-row"></tr>
            <tr class="toggle-row"></tr>
        </tbody>
        <tbody>
            <tr id="2" class="default"><tr>
            <tr class="toggle-row"></tr>
            <tr class="toggle-row"></tr>
            <tr class="toggle-row"></tr>
        </tbody>
        <tbody>
            <tr id="3" class="default"><tr>
            <tr class="toggle-row"></tr>
            <tr class="toggle-row"></tr>
            <tr class="toggle-row"></tr>
        </tbody>
</table>

I want to toggle the table-row class only when a default class row is clicked within its respective tbody.

The TypeScript file associated with this template is as follows:

import { Component, OnInit } from '@angular/core';
import { DataServiceService } from "../../services/data-service.service";
@Component({
  selector: 'app-projects',
  templateUrl: './projects.component.html',
  styleUrls: ['./projects.component.css']
})
export class ProjectsComponent implements OnInit {
  private teamMember: any[];
    public toggle = false;
  constructor(private dataserve: DataServiceService) { }
  ngOnInit() {
     this.dataserve.getTeamMemberData()
      .subscribe(
          (data: any) => {
                        var localarray= [];
                        for (let key in data){
              localarray.push({key:key, Value:data[key]});
            }
                        this.teamMember = localarray;
                        console.log(this.teamMember);
                    }
            );
  }
  Toggle(value){
    this.toggle = !this.toggle;
  }
}

Answer №1

For each row to function correctly, it is necessary to move the toggle variable inside the member.Value.subTasks variable.

Since the toggle variable is global, it will only update the view for all rows together.

 <ng-container *ngFor = "let subtask of member.Value.subTasks">
            <tr class="toggle-row" *ngIf="subtask.toggle" > 
                    <td>
                        {{ subtask.taskType }}
                    </td>
                    <td *ngFor="let hrs of subtask.subtaskHoursLogged">
                        {{ hrs }}
                    </td>
            </tr>
        </ng-container>

In order for everything to work properly, the Toggle(i) function needs to be modified to update the member.Value.subTasks variable accordingly.

I hope this explanation helps!

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

Breaking apart a string and mapping it to specific fields

My issue is relatively straightforward. Upon loading my page, a long string representing an address is generated. For example: 101, Dalmations Avenue, Miami, Florida, USA, 908343 With the help of jQuery, I can split the string using: var address = sel.o ...

Nodemailer attachments are missing contents

I'm having trouble attaching files to emails using NodeMailer. When I check the sent email, the attachments appear as empty files with 0 bytes. Even when I download them, they are still empty text files. Can someone please help me identify what I migh ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...

The Bootstrap toggler is failing to conceal

Currently, I am working on a website utilizing Bootstrap 5. The issue arises with the navbar - it successfully displays the navigation when in a responsive viewport and the toggler icon is clicked. However, upon clicking the toggler icon again, the navigat ...

Authorization setup encountered an issue: an unexpected character was found at the beginning of the JSON data on line 1, column

I'm currently in the process of setting up a login page for users on my website, using mongoose, express, bcrypt, and nodejs. However, I am encountering an issue when trying to input the username and password. The error message that I receive is as fo ...

Is NGX Extended Pdf Viewer the Ultimate Solution for Acrofields?

Can a universal solution be developed for PDF Forms? The example in the documentation suggests this, but the acrofield names and their quantities are already known here public firstName = 'Jane'; public lastName = 'Doe'; public country ...

Searching for objects with distinct hash codes using an AngularJS filter

My title may be long, but I want to explain something: I am using a service called: divisionService This service has a function that returns a list of all Divisions in my system. I use this list to populate a select: <select class="form-control ...

How can I ensure a mock is resolved before rendering in React with Jest?

By default, the loading state in my react component is set to true, and then it changes to false after a fetch call. Within my jsx code, I have a conditional check like {!loading && which functions correctly. However, during testing, the fetch call is mock ...

Encountering the error message "Uncaught Error: Objects are not valid as a React child" even though I am not passing objects as children in my React component

My current challenge involves mapping an array of objects, which I retrieved from an axios.get request and then passing them as children to React components. The error message that's causing trouble for me reads as follows: An Error occurred: Objects ...

What is the process for unsubscribing through an HTTP post request within an Angular application

There is a POST API set up through API Gateway on AWS, but it seems to be returning an infinite loop of arrays, as shown in the image below. How can I make it return just one array? Multiple requests Below is the code snippet: Angular import { Componen ...

accessing various tiers of data through an application programming interface

Currently, I have successfully accessed 5 followers of a GitHub user via AJAX. I am now attempting to delve three levels deep into each of the initial 5 followers, retrieving 5 more followers at each level. Essentially, the goal is to return 5 followers, t ...

Null response received from HTTP GET request

Currently, I am working on a project using ASP.NET with Angular 6 in the frontend, but I am facing some difficulties trying to understand what is going wrong. In short: I am receiving an empty JSON response even though the backend is sending the correct va ...

React Native encountered an error: `undefined` is not an object

Encountering the commonly known error message "undefined is not an object" when attempting to call this.refs in the navigationOptions context. Let me clarify with some code: static navigationOptions = ({ navigation, screenProps }) => ({ heade ...

Alert: A notification appears when executing Karma on grunt stating that 'The API interface has been updated'

While executing karma from a grunt task, I encountered the following warning: Running "karma:unit" (karma) task Warning: The api interface has changed. Please use server = new Server(config, [done]) server.start() instead. Use --force to continue. A ...

Filtering out undefined elements from an array created by mapping over a nested array using map() and filter()

I'm currently in the process of creating multiple variables to be utilized later on, each one representing a specific array within a set of nested arrays (essentially a data array that will be used for various projects). As I attempt to select the pr ...

Implementing a Jquery check based on a checkbox

Hey, I'm having an issue with a condition. When I uncheck the checkbox, it doesn't uncheck. I've tried to make a block display, but the JavaScript isn't working. I attempted to add: document.getElementById("Reload").style.display = "b ...

Getting the text from an HTML input field requires accessing the value property of the

My goal is to generate a pdf report using php. The user will enter their name in an input box, which will then be passed to the second php page that searches the mysql database. Issue: When the user inputs their name, attempting to retrieve the data (var ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

When attempting to import Quill-blot-formatter with react-quill via next/dynamic, the registration process fails and continues to display a loading message

After creating a function component and configuring quill-blot-formatter with react-quill, I added the blotFormatter to the modules list. Then, I imported this module using next/dynamic on the desired page. The custom function looks like this: import Reac ...

Tips on adding a select tag option value to an Angular 4 web service

I am currently working on a web service that allows me to post data in order to create profiles. I have encountered an issue with a drop-down list in the form where the selected option value does not get posted. This results in an 'undefined' err ...