Utilizing the Angular *ngFor directive to iterate through JSON data

Just stepping into the world of Angular, I want to share a brief overview of my goal since the code is lengthy. Here's the relevant part:

Within my project, I have a list display component.

And I have two components, namely animals and zone.

For instance:

zone comprises of 2 columns - zone name and zone code,

While animals consists of 3 columns - animal code, animal name, and animal zone

and so forth (imagine 10 other components as well)

Every component generates JSON data and sends it to the display list component.

The display list component then parses the JSON and renders it using ngFor.

In essence:

  1. Each component creates JSON and sends it to a service with a behavior subject
  2. The service, with a behavior subject, receives the JSON
  3. The display component fetches the latest JSON from the service's behavior subject
  4. Finally, the display component parses the JSON and displays it using ngFor

I have managed to generate and send JSON to the display list component effectively.

For instance, I can showcase the JSON data from the zone component which is then sent to the display component.

https://i.sstatic.net/4oO1L.png

I seek your guidance in processing the JSON data so that I can seamlessly display it on the display component's HTML using ngFor.

Code:

data.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private messageSource = new BehaviorSubject(null);
  currentMessage = this.messageSource.asObservable();
  constructor() { }
  changeMessage(message: any) {
    console.log('changed');
    console.log(message);

    this.messageSource.next(message);
  }
}

for zone (zone.component.ts) : [car.component.ts is identical to zone.component.ts, don't be confused]

import { Component, OnInit } from '@angular/core';
import { DataService } from "../../services/data.service";
import { Router } from '@angular/router';

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

  jsonData: any;
  data: any;

  constructor(private router: Router, private dataService: DataService) {
  }

  dd() {
    this.setData(this.jsonData);
  }

  ngOnInit(): void {
    this.setJsonData();
  }

  async getJsonData() {
    const myurl: string = "http://localhost:3000/zone/get/all";
    const response = await fetch(myurl, { headers: { 'Content-Type': 'application/json' } });
    return await response.json();
  }

  async setJsonData() {
    this.jsonData = await this.getJsonData();
  }

  setData(newJsonData: any) {
    this.data = Object.entries(newJsonData);
  }

  navigateToDisplayList(){
    this.router.navigateByUrl('display-list');
  }

  newMessage() {
    this.dataService.changeMessage(this.jsonData);
    // console.log(this.jsonData);
    // console.log(this.data);
    this.navigateToDisplayList();
  }
}

for display : display-list.component.ts :

import { Component, OnInit } from '@angular/core';
import { DataService } from "../../services/data.service";

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

  data: any;

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.dataService.currentMessage.subscribe(message => this.data = message);
  }

  dd(){
    console.log(this.data);
    document.body.innerText = this.data.toString();
  }
}

A special note:

Please refrain from suggesting to capture the JSON in a variable and then loop through console.log(object.zonename). Due to the varying JSON content across 30 components, direct HTML display from JSON is essential.

Thank you for your understanding.

Answer №1

After carefully considering the feedback, I have updated my response....I see that you are interested in accessing the key-value pairs within the object. This can be achieved by implementing the following code snippet:

<div *ngFor="let item of items">
        <span *ngFor="let keyvalue of item | keyvalue">
            {{keyvalue.key}}:{{keyvalue.value}}
        </span>
</div>

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

End the pipeline execution in a chain of RxJS observables

Here is a scenario where a series of Observables are chained together. Is it possible to prevent the subsequent chain from executing if an error is thrown by 'parentObs1'? import { throwError } from "rxjs"; import { mergeMap, catchError ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

Retrieve the value of a JsonNode without having to search through its child nodes

Here is the structure of the resource I am dealing with: "activity": { "activity_type": "Like", "activity_id": "123456", "object_id": "", "product_id":"", "reference_activity": { ...

How can I retrieve the value of a radio button using jQuery

My goal is to retrieve the selected/checked radio button value using the .get function. I believe my code is correct, but the sequence seems to be off. $.get('burgerorder_check.php', function(data) { inputVal = $('input[type ...

Enhancing URL Strings with AJAX

Currently experiencing a problem with an AJAX call using JSONP that is failing without any reported reason. We are closely monitoring the server being called and have noticed that AJAX is appending to the URL, which may be contributing to our difficulties. ...

Learn the steps to refresh a component in Angular 5

src/shared.service.ts public _testData:any;   set testData(value:any) {     this._testData = value   }   get testData():any {     return this._testData;   } src/header.component.ts private postValues( ...

determine the height of a div using jquery calculations

If a div is positioned relative and contains child divs that are positioned absolute, the parent div will have no set height. However, if the contents of the div change dynamically, there should be a way to calculate and adjust the height of the parent acc ...

I'm curious if there is a method to implement Angular Datatables that includes a filter for every column in a more streamlined and efficient manner?

Incorporating Angular 7 and Angular DataTables "the angular way", I aim to implement individual column filters similar to "Individual column searching" as demonstrated here: , which is presented as a non-angular approach. My attempts to merge "the angular ...

What are the steps for creating a TypeScript version of a custom CKEditor5 build?

Currently, I am in the process of creating a personalized version of CKEditor5. By following the guidelines provided in the official documentation, I successfully obtained ckeditor.js. My goal now is to produce a typescript file (ckeditor.ts or ckeditor.d ...

Having trouble with Node JS res.redirect() not functioning as desired?

I'm attempting to use res.redirect() to redirect to an external URL, but the host name isn't being replaced. For example: My current URL: https://example.com Desired redirect URL: When I use res.redirect("https://example-2.com/pqr?par=123 ...

Having trouble retrieving the component state within AgGrid's cellRenderer

When working on my React app using functional components, I encountered an issue with accessing a local state (myObj) within a cellRenderer in AgGrid. The local state is populated via a context object from the parent component based on an API response. Un ...

JQueryMobile 1.3.2 encounters issues with popups following the installation of Chrome version 43.0.2357.65 m update

Is anyone else experiencing issues with the latest version of Chrome "43.0.2357.65 m" causing problems with JQueryMobile 1.3.2? When I try to click on a popup, it suddenly jumps to the top of the page and the scroll bar disappears. This was not an issue in ...

Limitations on Embedding Videos with YouTube Data API

I have been using the Youtube Data API to search for videos, but I am encountering an issue with restricted content appearing in the results. Specifically, music videos from Vevo are showing up even though I only want videos that can be embedded or placed ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Creating dynamic HTML with Angular 2 using property binding

After retrieving an HTML string from the database, I came across html='<span>{{name}}</span>' where 'name' is a component property. I am looking to display this string in HTML while maintaining the name binding. I have expl ...

Guide to incorporating HTML within React JSX following the completion of a function that yields an HTML tag

I am currently working on a function that is triggered upon submitting a Form. This function dynamically generates a paragraph based on the response received from an Axios POST request. I am facing some difficulty trying to figure out the best way to inje ...

GruntJS is piecing together a JSON file using a helper to break it down into

Currently, I am looking to implement a custom helper that will allow me to parse an entire JSON file into a partial. While the technique from this site has been helpful: Parsing Json data into partial I have found that it works well for parsing individua ...

What is the best way to import a geojson file into Express.js?

I'm currently trying to read a geojson file in Node.js/express.js. The file I am working with is named "output.geojson". I want to avoid using JSON.parse and instead load it using express.js (or at least render it as JSON within this function). var o ...

Having difficulty configuring my Angular .NET Core 2.1 web application correctly on GoDaddy

After deploying my netcore 2.1 Angular application using Visual Studio FTP profile to my Godaddy Host, I encountered a few issues. The deployment included the following contents: ClientApp folder wwwroot appsettings.json application.dlls web.config In t ...

Unsteady movement of Three JS OrbitControls during rotation

Currently, I am working on a scene with three.js and using orbit controls to rotate the camera around the scene. Occasionally, while rotating, the camera starts moving erratically before calming down and rotating smoothly again. I have read about orbit co ...