Discover how to extract a specific piece of data from a JSON file using Angular 2+ framework

I've been working on a code that parses JSON data and populates a table using ngFor.

Here's an example of what the output looks like:

https://i.sstatic.net/xDlOa.jpg

So far, I've successfully listed the data in the table.

But now, I'm wondering how to extract and display a single piece of data based on a specific ID.

For instance, if I want to retrieve the name corresponding to id=3, it should be "Edward".

I'm stuck on this, and I need some guidance or assistance. Can anyone help me out?

Thank you.

app-components.ts

import { Component } from '@angular/core';
import {Http, Response} from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

    private data;

    constructor(private http:Http){
    }

    ngOnInit(){
        this.getData();
    }

    getData(){
        this.http.get('/localhost/data.json')
                .subscribe(res => this.data = res.json());
    }

}

app-component.html

<table>
    <tr>
        <th>#</th>
        <th>Name</th>
        <th>Amount</th>
    </tr>
    <tr *ngFor="let info of data">
        <td>{{info.id}}</td>
        <td>{{info.name}}</td>
        <td>{{info.amount}}</td>
    </tr>
</table>

data.json

[  
   {  
      "id":"1",
      "name":"John",
      "amount":"112"
   },  
   {  
      "id":"2",
      "name":"Maria",
      "amount":"44"
   },  
   {  
      "id":"3",
      "name":"Edward",
      "amount":"40"
   }
]

Please let me know if the information provided is adequate.

Answer №1

To achieve this, you can utilize the <ng-container> element. This is necessary because you cannot apply two directives to a single element, like when using both *ngIf and *ngFor.

<table>
    <tr>
        <th>#</th>
        <th>Name</th>
        <th>Amount</th>
    </tr>
    <ng-container *ngFor="let info of data">
    <tr *ngIf='info.id == 3'>
        <td>{{info.id}}</td>
        <td>{{info.name}}</td>
        <td>{{info.amount}}</td>
    </tr>
    </ng-container>
</table >

Check out a working example here

Answer №2

Have you considered creating a separate component to output just one table row instead of using an *ngIf directive?

Here is an example:

<table>
    <tr>
        <th>#</th>
        <th>Name</th>
        <th>Amount</th>
    </tr>
    <tr>
        <td>{{info.id}}</td>
        <td>{{info.name}}</td>
        <td>{{info.amount}}</td>
    </tr>
</table> 

Your table.component.ts file will look like this:

@Input() info : any;

Now, you can loop over the

<app-table [info]='info'></app-table>
inside your app-component.html. You can also pass specific information by using
<app-table [info]='info[3]'></app-table>
.

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

What steps are needed to enable WebStorm's autocompletion for external libraries?

As a beginner user of WebStorm and TypeScript, I am currently experimenting with incorporating the libstl library into my code. The snippet below is what I have written so far: var PriorityQueue = require('libstl').PriorityQueue; var queue = ne ...

Node.js server-side storage solutions for integration with Dojo

Currently, I am working on developing a new application. It is my first time creating a single-page AJAX application that solely relies on Restful stores. So far, I have written some code and executed simple queries using the GET method. To maintain organ ...

Invoking a functionality within a stream of events through an observable's subscribe

Service2.ts public flags$: BehaviorSubject<FlagName> = new BehaviorSubject<FlagName>("custom-flag-1"); This flag is set up as follows: private _setFlags = () => { const flagsData = this._customClient.getFlags(); if (f ...

How can I access the data variables from a JSON request within a function?

My task involves loading multiple JSON files from an array called bunchOfData, with each file having a corresponding URL. How can I access my variable "myI" within the processData function? for(var i = 0; i < bunchOfData.length; i++){ $.getJS ...

Associate union with interface attributes

Can a union type be transformed into an interface in Typescript? My Desired Outcome If we have a union type A: type A = 'one' | 'two' | 'three'; I want to convert it to interface B: interface B { one: boolean; two ...

The error message "Ionic 3 encountering issues with accessing property 'valid' from undefined or null reference"

As I was setting up a form on a CRUD using Firebase, initially just storing name and number as string types, I decided to add more parameters of the same type. However, I encountered an issue with the error message "Unable to get property 'valid' ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...

Should a MEAN stack app require the use of two servers in order to run?

Currently, I am in the process of developing a MEAN stack application which involves using MongoDB, ExpressJs, Angular 6, and NodeJs. One issue I am facing is determining whether two servers will be necessary to run the app simultaneously. Specifically, o ...

What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...

Angular animation triggered when a specific condition is satisfied

I am working on an animation within my Angular application @Component({ selector: 'app-portfolio', templateUrl: 'portfolio.page.html', styleUrls: ['portfolio.page.scss'], animations: [ trigger('slideInOut&apo ...

Using AWS Athena with Java to retrieve data from columns of struct type

In Athena, I have created a table that maps some data stored in an AWS S3 bucket. One of the columns in this table is of type array containing objects (struct). CREATE EXTERNAL TABLE traceroute ( af int, dst_addr string, dst_name string, ` ...

Convert Parse.com data into a JSON string format and then reverse the process

Currently, I am utilizing PushWoosh for sending custom data and would like the capability to send a ParseObject from one user to another. It seems that this can only be done by converting the ParseObject into a JSON string first, and then converting it bac ...

What is the reason that TypeScript cannot replace a method of the base class with a subtype?

Here's a straightforward example. type Callback<T> = (sender: T) => void; class Warehouse<T> { private callbacks: Callback<T>[]; public constructor(callbacks: Callback<T>[]) { this.callbacks = callbacks; ...

Ensure that Vuex state can only be accessed through a getter function

Our goal is to have a variable in our Vuex store that can only be accessed through the getter function. To do this, we must ensure that the variable is protected from external access outside of the store. What options are available to us? ...

Steps to extracting the JSON file from a pre-existing Google Map

I am looking to develop a customized Google Map search tool using the Google Maps API. I am curious if it is possible to extract the JSON data from a map created using the native Google Map management system, like this one: https://www.google.com/maps/d/v ...

What is the process for deploying a .NET Core + Angular single page application to multiple environments?

After utilizing the Angular project template with ASP.NET Core in Visual Studio 2019, I developed an application that includes multiple environments: DEV, STG, and Production. Each environment corresponds to specific "appsettings.json" files for the .NET p ...

Potential security risks involved in utilizing content from multiple domains in client-side scripts

Seeking to load external content into a div on my page using jQuery's load function has been successful with local content, but not with content from outside domains. $("#result").load("http://extrnal.com/page.htm #data); (In IE, it does work with a ...

Restrict or define the acceptable values for a key within an interface

In search of defining an interface that allows for specific range of values for the key. Consider this example: interface ComparisonOperator { [operator: string]: [string, string | number]; } The key can take on values such as >, >=, !=, and so ...

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

Personalize JSON Output

Currently, I am working on incorporating jqvmap into my project. The original format of my json response is as follows: [ { "Count": 10, "ProvinceCode": 34 }, { "Count": 6, "ProvinceCode": 59 } The required format for jqvmaps is as shown ...