Navigating through JSON object using Angular 2's ngFor iterator

I want to test the front end with some dummy JSON before I write a service to get real JSON data. What is the correct way to iterate through JSON using ngFor? In my component.ts file (ngOnInit()), I tried the following code with a simple interface:

var jsonSample = {
    "name": "sample1",
    "content": [
    {
      "id": "3",
      "name": "Test",
      "value": "45"
    }, 
    {
      "id": "4",
      "name": "Test2",
      "value": "60",
    }]
}

var items: Array<IContent> = jsonSample.content;

Then in the HTML:

<tr *ngFor='let content of items'>
      <td>{{content.name | lowercase}}</td>
      <td>{{content.id}}</td>
      <td>{{content.value}}</td>
</tr>

Is it better to use JSON.parse instead?

Answer №1

It looks like your *ngFor loop is correctly traversing the json object. There's no need to use JSON.parse in this scenario since you're working with an object directly.

If you're expecting a response from a service, refer to this documentation. You will utilize res.json() to parse and extract JSON data from the Response object.

Answer №2

That makes perfect sense! All I needed to do was modify:

let list: Array<IContent> = jsonData.content;

to

list: IContent[];
this.list = jsonData.content;

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

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Having difficulty transmitting data from a view to an API controller

Hey there! I'm currently working on sending JSON data to the API controller through a HttpPost request to add that data to a file. This is what my JSON File looks like: { "students": [ { "Id": 1, "Name": "Ra ...

Keycloak is having trouble interpreting the value returned by my ID provider. How can I resolve this issue?

I'm currently integrating Keycloak with an external OAuth server serving as the identity provider. During the login process, Keycloak initiates an authentication backchannel request and expects a JWT response from the OAuth server. However, when att ...

I keep encountering a syntax error every time I attempt to run the yarn start command

Upon attempting to execute yarn start, an error appeared in the command line indicating a syntax error. I have already attempted updates on both node and yarn. $ node --max_old_space_size=8192 ./node_modules/.bin/ng serve -H 0.0.0.0 --disable-host-check ...

Is it possible to switch the hamburger menu button to an X icon upon clicking in Vue 3 with the help of PrimeVue?

When the Menubar component is used, the hamburger menu automatically appears when resizing the browser window. However, I want to change the icon from pi-bars to pi-times when that button is clicked. Is there a way to achieve this? I am uncertain of how t ...

Bypassing Python JSON loop interruption

Struggling to work with the MusicBrainz API using python and facing challenges figuring out why a loop won't break after meeting a specific condition. Passing song duration and acoustic ID through a URL fetching JSON data. Uncertain about JSON validit ...

Creating a universal timer at the application level in Angular

Is there a way to implement a timer that will automatically execute the logout() function in my authentication.service at a specific time, regardless of which page I am currently on within my application? I attempted to create a timer within my Authentica ...

best practices for creating space between flexbox items

My task involves presenting a continuous scroll list of scheduled jobs using Angular Material. Each item in the list needs to be divided into three columns utilizing flexbox. Despite my efforts, I am struggling with adding space between the columns within ...

Incorporate a script into your Angular-CLI project

Can you guide me on inserting a script file into the index file of an angular2 project that was generated using angular-cli? : <!doctype html> <html> <head> <meta charset="utf-8"> <title>MyAngularApp</title> ...

Guide on executing .ts script file and building angular 5 with NPM

I am facing an issue with running a file that has a .ts extension before executing npm run build to build my Angular 5 project. package.json "scripts": { "ng": "ng", "start": "ng serve", "compile": "npm-run-all myts build", "myts": "ts-no ...

The function that was provided as a parameter is not functioning as expected

I have a WsConnector class responsible for connecting to my backend application and subscribing to a WebSocket topic. export class WsConnector { private stompClient: any; connect(onMessage: (msg) => void) { this.stompClient = Stomp.over ...

Construct the output directory according to the specific environment

I'm exploring the process of constructing and launching an Angular 2 project using angular cli with variables specified in my environment typescript files. For instance, within my angular-cli.json file, there is a dev environment linked to "environme ...

The $.getJSON function seems to be malfunctioning and is not returning the expected data, instead, showing [object Object

I seem to be encountering a common issue with my ajax call not retrieving the JSON data. It appears that it may be due to an array and not using the correct index, although I am indeed utilizing an index on the front-end. Despite trying various solutions f ...

How can @ngrx be utilized to retrieve data based on the route?

Our webapp requires users to click through lists to reach a specific edit view. For example, starting from the landing page, a user selects a client, then an agent, and finally reaches the edit view of that agent. The URL in this scenario would contain the ...

Storing search results from tweets into a MongoDB database using Python

I am attempting to store tweet search results in MongoDB using the code below: import json import tweepy from pymongo import MongoClient ckey = '' consumer_secret = '' access_token_key = '' access_token_secret = '&apos ...

Angular: utilizing input type="date" to set a default value

Looking for a way to filter data by date range using two input fields of type "date"? I need these inputs to already display specific values when the page loads. The first input should have a value that is seven days prior to today's date, while the ...

Return the subclass from the constructor function

class X{ constructor(input: string) { // do things } f() {console.log("X")} } class Y extends X{ constructor(input: string) { // do things } f() {console.log("Y")} } class Z extends X{ con ...

'Error: Script ngcc is missing in NPM' - Issue encountered

Out of nowhere, my Visual Studio Code project suddenly began showing two strange errors like this: click to view image All the tags from Angular Material are now being marked as errors, failing to get recognized as valid tags. Attempting to use npm run n ...

Create categories for static array to enable automatic suggestions

I have a JavaScript library that needs to export various constants for users who are working with vscode or TypeScript. The goal is to enable auto-complete functionality for specific constant options. So far, I've attempted to export a Constant in th ...