Exploring the power of displaying JSON Arrays in an Angular 2 TypeScript front end using the *ngFor directive

Here is a simple front-end page using Angular 2:

       <table class="table">
          <tr>
              <th>title</th>
              <th>description</th>
          </tr>
          <tr *ngFor="let notes of Note">
              <td>{{notes.title}}</td>
              <td>{{notes.body}}</td>
          </tr>
      </table>

Below is the component code with Note model:

export class Note {
  noteId:  number ; 
  title:  String ;
  body: String ;    
  color:  String ;
  isArchive:  boolean ; 
  isPinned:  boolean ; 
  isTrash: boolean ;
}



notes:Note[]=[];

ngOnInit() {
  this.getAllNotes();
}

getAllNotes(){
this.noteService.getNotes()
.subscribe(
data => {
  console.log("notes get");
  console.log(data._body);
  this.notes=data._body;
  console.log("notes array");
  console.log(this.notes);
},
error => {
  console.log("notes error");
    console.log(error);

});
}

The output of this.notes is shown below:

[
  {
    "noteId": 5,
    "title": "hi ",
    "body": "ragini",
    "color": null,
    "createDate": 1515820245951,
    "lastUpdated": 1515820245951,
    "reminder": null,
    "image": null,
    "collaborator": [],
    "labels": [],
    "user": 1,
    "archive": false,
    "pinned": false,
    "trash": false
  },
  {
    "noteId": 8,
    "title": "s",
    "body": null,
    "color": null,
    "createDate": 1515820746348,
    "lastUpdated": 1515820746348,
    "reminder": null,
    "image": null,
    "collaborator": [],
    "labels": [],
    "user": 1,
    "archive": false,
    "pinned": false,
    "trash": false
  }
]

Now, let's see how to display this data in the Angular 2 front-end.

Answer №1

Make sure to utilize notes rather than Note

<tr *ngFor="let note of notes">
    <td>{{note?.title}}</td>
    <td>{{note?.body}}</td>
</tr>

VIEW DEMO

Answer №2

Snippet of HTML code:

<tr *ngFor="let notes of notes; let i = index">
    <td>{{notes.title}}</td>
    <td>{{notes.body}}</td>
</tr>

I recently used the code this.notes=JSON.parse(data._body); and everything else is as shown above.

data => {
    console.log(data._body);
    this.notes=JSON.parse(data._body); // applying parse function here
    console.log("notes array"+this.title);
    console.log("Title :: "+this.notes.title);
},

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

Parsing precise decimal values from JSON file using Java

I have a JSON document structured like this. { "name": "Smith", "Weight": 42.000, "Height": 160.050 } To process this file, I've created the following Java code. import org.json.simple.JSONOb ...

Can a package be published with an ambient module declaration?

Currently, I am dealing with a package that contains numerous generated modules all exporting the same type, such as an icon library. I am trying to avoid the tedious task of creating individual .d.ts files for each module since they would essentially be ...

The type of the element is implicitly 'any' due to the fact that an expression of type '"name"' cannot be used to index the type 'Object'

There is an implicit 'any' type used for the element because the expression of type '"name"' cannot be indexed in type 'Object'. this.resto.getCurrentResto(this.router.snapshot.params['id']).subscribe((resu ...

How can I implement conditional validation in Angular reactive forms for nested form groups and form controls

I'm working on creating a new User Form. To clarify, if the user selects the medical policy checkbox, they will need to provide details about their medical policy. Below is the code for the user form group: let userForm = this.myFormBuilder.group ...

Having trouble with the ag-grid demo - grid not displaying as intended

Struggling to wrap my head around the "ag-grid" Typescript grid component for use in my Angular 6 applications. The website seems promising, but I am having trouble getting their "Getting Started" demo to function on my setup. I followed all the setup st ...

What is the best way to distinguish between various objects that are all in a single line?

After creating an array of objects with data such as name and id, I used the res.json() method to convert it into json format for browser use. However, when I input the array of object data, it looked like this: [ { id: 1, name: 'albany sof ...

Using Angular HTTP PUT Method to Upload Files/Images to the S3 Server

Working on my Angular project, I'm facing an issue with uploading files or images to an S3 server using the http.put method. Below is the code snippet that I have written: uploadFileToS3(fileUrl: string, file: File): Observable<any> { const ...

What is the best way to implement pojo in conjunction with an asynctask for parsing

I'm using AsyncTask to fetch data from https://jsonplaceholder.typicode.com/users, but I want to utilize a POJO object. What code should I add in between? What line of code should I write and how should I write it? DataRetriever.java public DataRet ...

Mapping the Observable returned from an Http request in Angular: A Step-by-Step Guide

I'm facing a problem with the code below, as it is returning an empty array. I need help understanding why this is happening. What is the best way to push objects to an array from a return Observable? Here is the code snippet from jobServices.ts: g ...

Having difficulty transmitting extensive data in a Jquery ajax request

Hello, I'm currently working on a MVC4 application where I am saving values to a Database. However, I encountered an error stating: "The request filtering module is configured to deny a request where the query string is too long." I am using an Ajax ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Searching with specified fields and assigned identifiers using ElasticSearch

I am looking to search my users in ElasticSearch by matching multiple fields and their document IDs. The current code I have successfully matches multi fields, as shown below: { "query" : { "multi_match": { "fields": [ ...

Icons in IE11 are lagging behind other browsers in terms of rendering and loading speed

In my Angular 5 application, I am using SVG icons across the site. While they load properly in Chrome, Mozilla, and Safari, there seems to be an issue with IE11 where the icons don't load. To address this, I included svgxuse in my pollyfill.ts file. ...

Angular 2's abstract component functionality

What are the benefits of utilizing abstract components in Angular 2? For example, consider the following code snippet: export abstract class TabComponent implements OnInit, OnDestroy {...} ...

Facing an issue with displaying a component error in a mat-form-field in Angular 9

I am looking to develop a shared component for displaying errors in Angular Material. Here is my shared component pfa-share-error: <mat-error *ngIf="fieldErrors(fieldName).required && fieldErrors(fieldName)"> Required </mat-err ...

The conversion to ObjectID did not succeed due to an issue on the front end

I have encountered an issue while trying to send a post request to create a task within a list using an API provided to me. This error occurs when I attempt to make the request in postman. Below is the schema of the post request body required by the API, ...

Tips for successfully integrating cache invalidation in an Angular Server-Side Rendering setup

I'm currently facing a challenge with cache busting in my Angular application. Despite trying to implement it, the cached version of the website keeps appearing to users unless cookies are cleared. I'm looking for a solution to automatically cle ...

Translate array into object with correct data types (type-specific method)

Welcome In our project, we have implemented attributes support where each attribute acts as a class. These attributes include information on type, optionality, and name. Instead of creating an interface for every entity, my goal is to automate this proces ...

Changing HTML lists into JSON format

I am facing a slight issue with my HTML template while trying to convert it to JSON. My goal is to convert a list of HTML messages into JSON format. I appreciate your assistance in advance. HTML Template <div class="message"> <div class="mes ...

Tips for customizing the appearance of date and time formats

Does anyone know how to retrieve this specific time format using Angular2 TypeScript? 2016-9-25T05:10:04.106Z I've tried searching online but couldn't find a straightforward solution. When attempting this in TypeScript, the following results a ...