Toggle the visibility of a component by clicking on a specific title within a table, dependent on the column title in Angular 9

Currently, I am developing an Angular application focused on creating a COVID-19 tracking app.

In this project, I have designed 2 components - Component A displays a list of all states, while Component B lists all districts within a particular state.

To view my work so far, you can visit my StackBlitz link here.

The expected output for my app is similar to the layout found at this link.

When working on this project, I referred to a solution on Stack Overflow which can be found here.

My current challenge involves displaying data in table format. When a state is clicked, it should show all the relevant information, and clicking it again should close that section. Similarly, if another state is selected, the district under that state should be displayed.

However, I am facing issues with where to place my

<app-componentB></app-componentB>
. Whenever I try to include it within a loop, the same list of districts gets repeated under each state.

Below is a snippet of my code:

componentA.html

  
 <tbody *ngFor="let data of statewisedata;let i=index">
    <span class="dropdown rotateDownRight"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg></span>

    <tr class="state">
        <td (click)="OngetState(data.state)" style="font-weight: 600;">{{data.state}}</td>

        <td style="color: inherit;">{{data.confirmed}}
            <span *ngIf='DailystateStatus[i]?.confirmed !==0 || DailystateStatus[i]?.confirmed < 0 ;' class="deltas" style="color: rgb(255, 7, 58);"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></svg> {{DailystateStatus[i]?.confirmed}}</span>
        </td>

        <td style="color: inherit;">{{data.active}}</td>
        <td style="color: inherit;">{{data.recovered}}</td>
        <td style="color: inherit;">{{data.deaths}}</td>
    </tr>

    <app-district *ngIf="!showDistrict"></app-district>
</tbody>

componentA.ts

 
showDistrict=true
OngetState(state) {
    this.cs.getState(state)
    this.cs.getDataDistrictWise(state)
    this.showDistrict=!this.showDistrict
}

Answer №1

After making a few adjustments, your code should look like this:

**componentA.html**

            <tbody *ngFor="let data of statewisedata;let i=index">
                <span class="dropdown rotateDownRight"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg></span>

                <tr class="state">
                    <td (click)="OngetState(data.state); showHideData(data)" style="font-weight: 600;">{{data.state}}</td>



                    <td style="color: inherit;">{{data.confirmed}}

                        <span *ngIf='DailystateStatus[i]?.confirmed !==0 || DailystateStatus[i]?.confirmed < 0 ;' class="deltas" style="color: rgb(255, 7, 58);"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline>
                                </svg>    {{DailystateStatus[i]?.confirmed}}</span>

                    </td>


                    <td style="color: inherit;">{{data.active}}<</td>
                    <td style="color: inherit;">{{data.recovered}}</td>
                    <td style="color: inherit;">{{data.deaths}}</td>

                </tr>
                <app-district *ngIf="data['show']"></app-district>
            </tbody>



**component.ts**

  OngetState(state) {

    this.cs.getState(state)
    this.cs.getDataDistrictWise(state)
    // this.showDistrict=!this.showDistrict
  }

 showHideData(data) {
    if(data && data['show'] == true) {
      data['show'] = false;
    } else {
      data['show'] = true;
    }
  }

Answer №2

I suggest exploring the options provided in the mentioned reference.


    <tr>

     <td (click)="OngetState(data.state,i)" style="font-weight: 600;">{{data.state}}</td>

    <td>...</td>
    <td>...</td>
    <td>...</td>
    </tr>

<app-district *ngIf="selectedIndex == i && showDistrict==true"></app-district>

component.ts

selectedIndex = -1;
  showDistrict:boolean=false

OngetState(state,i) {
    console.log(this.showDistrict)
    this.cs.getState(state)
    this.cs.getDataDistrictWise(state)
    this.selectedIndex = i;   
    this.showDistrict=!this.showDistrict
    console.log(this.showDistrict)
  }

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

Looking for a solution to fix the VueJS calculator that only works once?

My calculator project using VueJS, HTML and CSS is almost complete. However, I'm facing an issue where it only works once. For example, if I input 6x3, it correctly gives me 18. But if I then clear the result and try to input a new calculation like 3 ...

The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'. var records = ...

Angular2: Retrieve and process a JSON array from an API

I'm currently facing an issue with my service while attempting to fetch a json array from an api and showcase it on the page. I believe there might be an error in my code, but I can't pinpoint exactly where. getAuctions(): Promise<Auction[ ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

What is the best way to retrieve a variable within a nested function?

I'm struggling to access a variable from within a nested function in the following code: $(function() { var key = getRandomKey(dictionary); resetInputRow(dictionary[key]); $("#button").click( function() { var answer = key; ...

Using the prop callback in a React test renderer does not trigger updates in hooks

I am currently exploring ways to effectively test a React function component that utilizes hooks for state management. The issue I am encountering revolves around the onChange prop function not properly updating the state value of my useState hook. This in ...

Troublesome CSS conflicts arise when using minified assets with AngularJS and Webpack

After transitioning my Angular project to the Webpack build system, I encountered issues with Angular Dependency Injection in the JS source code. Surprisingly, now I am facing JS errors that are targeting CSS files, leaving me completely bewildered about w ...

Is Angular 5 capable of providing polyfill support for async/await in IE11?

Our software development team has created a program that requires support from IE11. Despite various sources indicating that IE11 does not support async/await, our simple Angular 5 project using async/await functions perfectly in IE11. This raises the ques ...

What could be causing this error to occur in my JavaScript React code?

ERROR - '}' expected. Parse error. I'm experiencing issues with this code snippet where I try to fetch data for a graph using React, but I keep getting the parse error mentioned above. vehiculoPorColores = () => { const _this = this fet ...

JavaScript Regex: Removing all characters that are not numbers

There have been several inquiries about this particular question, such as this one on Stack Overflow. Despite my efforts to replicate the solution and research regex, I can't seem to get it to work: $("#button").click(function () { new_number = $ ...

Issues arise when attempting to store data in an array in Angular using Typescript

Having an issue where my benchmark foreach loop is not correctly storing all values in the array. Instead, it only saves one value and returns a null error. Strangely, if I remove the push function and replace it with a console.log, all results are displ ...

Encountering an error with Gatsby while running the development environment due to issues with antd and less configuration (NPM

Encountering issues with the development server in local after installing antd, less, less-loader, gatsby-plugin-less, and gatsby-plugin-antd Versions: "gatsby-plugin-less": "^6.20.0", "less": "^2.7.1", "less- ...

Avoiding redundant requests with the same parameters in Angular/NGRX

Imagine having a component designed to showcase a list of actors from a movie. When this component loads, it triggers an action to retrieve the actors' data. actors.component.ts @Input() filter; // for example, only displaying male actors ngOnInit( ...

How to access and retrieve data from a USB flash drive using Javascript

I am looking to print PDF files from a USB flash drive. I have decided to use Mozilla Firefox and the R-kiosk plugin along with the open library PDF.js, but I am facing an issue. How can I read folders and files to create a tree structure without using ...

Unleashing the Power of RXJS: Discovering the Magic of connecting Events and Tapping into Executions with retrywhen

Whenever Angular attempts to establish a connection, I aim to display "Connecting". Although I can achieve this on the initial connection, I am uncertain about how to accomplish it when using retryWhen(). It is essential for me to intercept the actual exec ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

Complete a bootstrap row and begin a new row after every nth div element

I have a grid layout in Bootstrap that I will be filling with blog post thumbnails. <section class="container"> <div class="row thumbs"> <div class="col-sm-3">content</div> <div class="col-sm-3">content</div> ...

Navigating away from a guard in a module federated Angular application

My Angular application uses module federation with a route-guard that redirects to another route. Everything works fine when run as a standalone application, but I encounter an error when it is integrated into a shell application. The error states that the ...

Updating Data with Ajax in Laravel

Hey there, could you walk me through the process of updating with Ajax? I'm working with Laravel I prefer using HTML and Ajax only Here are my routes: Route::post('/post/homepage', 'AdminController@HomePage'); ...