Before utilizing in an Angular 6 template, it is essential to first parse the JSON content for the

I am currently working with Angular 6.

Within the component file, I have an array object defined.

items: Array<ItemData>;

The interface ItemData has the following structure:

export interface FavouriteProductData {
  id: number;
  type: string;
  content: string;
}

The content field contains data in a JSON encoded format.

'{"name":"Jonathan Suh","gender":"male"}';

When looping through the items in the template, I want to display the name field from the content.

<tr *ngFor="let i in items; id = index;">
  <td> {{ i.type }} </td>
  <td> {{ i.content.name }} </td>
</tr>

However, as the content is JSON encoded, I am facing difficulty displaying its contents in the template.

Is there a way to parse the JSON content within the template and store the parsed content in a new variable?

I attempted creating a method in the component:

jsonDecode(item) {
  return JSON.parse(item.content);
}

And then using it in the template like this:

<tr *ngFor="let i in items; id = index; p = jsonDecode(i)">
  <td> {{ i.type }} </td>
  <td> {{ p.name }} </td>
</tr>

Unfortunately, this approach does not seem to be effective.

Answer №1

Everything seems to be running smoothly with your initial approach example on Stackblitz

I made some minor modifications in the array variable declaration.

Component:

items : any =[];
name = 'Angular';
constructor(){
   this.items = [{id :'1', type :'spec' , content : '{"name":"Jonathan Suh","gender":"male"}'}];
}

extractNameFromJson(obj){
  obj = JSON.parse(obj);
  return obj.name;
}

HTML:

<tr *ngFor="let i of items;">
   <td> {{ i.type }} </td> 
   <td> {{ extractNameFromJson(i.content) }} </td>
</tr>

It is performing as anticipated so give it a go.

Answer №2

One possible solution involves storing the value retrieved from a typescript file in a variable and then using that variable on the HTML page for easy access.

For instance, save the fileTypeSelected variable in the TS file:

this.fileTypeSelected = JSON.parse(event)?.fileViewerType;

Then, you can use it in the HTML like this:

*ngIf="fileTypeSelected!='Something'"

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

Simple guide on implementing React with Typescript to support both a basic set of properties and an expanded one

I'm grappling with a React wrapper component that dynamically renders specific components based on the "variant" prop. Despite my efforts, I cannot seem to get the union type working properly. Here's a snippet of the code for the wrapper componen ...

Choose the appropriate NPM module platform for Angular development

My Angular application runs smoothly in Chrome, but encounters errors on Internet Explorer. The issue arises from the different distributions of NPM modules I install. For instance, within the kendo-angular-charts folder, we have: - dist |- cdn |- e ...

Retrieve information from API

When using my API, the data structure returned is as follows: {"msg":"List of all sales", "sales":[{"id":1,"user_id":3,"client_id":3,"description":"test","type":"test","status":"test","sale_date":"2020-04-01","payment_date":"2020-04-15","payment_ref":"tes ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Tips for troubleshooting the error message: "The relative import path "$fresh/dev.ts" is not prefaced with / or ./ or ../"

My editor is showing a TypeScript error for a Deno module I am working on. The import path "$fresh/dev.ts" should be prefixed with / or ./ or ../ I have an import_map.json file set up with the following content. { "imports": { "$fre ...

Having trouble adding the Vonage Client SDK to my preact (vite) project

I am currently working on a Preact project with Vite, but I encountered an issue when trying to use the nexmo-client SDK from Vonage. Importing it using the ES method caused my project to break. // app.tsx import NexmoClient from 'nexmo-client'; ...

In order to iterate through a 'IterableIterator<number>', you must either enable the '--downlevelIteration' flag or set the '--target' to 'es2015' or newer

While attempting to enhance my Slider, I encountered an error when utilizing TypeScript React within this Next.js project: "Type 'IterableIterator' can only be iterated through when using the '--downlevelIteration' flag or with a ...

The module "react-leaflet" is showing a type error because it does not have a exported member named "useEventHandlers"

My Next.js application is built with TypeScript and React-Leaflet. Everything runs smoothly when I start my development server using npm run dev, no errors whatsoever. However, the problem arises when I attempt to build the project using npm run build. An ...

Angular: Implementing a Dark and Light Mode Toggle with Bootstrap 4

Looking for suggestions on the most effective way to incorporate dark mode and light mode into my bootstrap 4 (scss) angular application. Since the Angular cli compiles scss files, I'm not keen on the traditional method of using separate css files for ...

Utilizing a fixed array as the data source for a mat-table

I am currently working on implementing the Angular Material table into my project. I am encountering an issue when trying to define the [dataSource]="data", even though I am using code similar to the examples provided. My question may seem basic, but my t ...

Guide on correctly importing the Monaco IStandaloneCodeEditor interface in Vue3 using the Composition API

While working with Monaco, I came across a challenge in defining the instance type for encapsulating a component package. I am unsure about how to import the interface IStandaloneCodeEditor | IStandaloneDiffEditor, or if it is necessary at all. <script ...

The TypeScript optional callback parameter is not compatible with the anonymous function being passed to it

Encountering an issue with TS callbacks and function signatures. Here is my scenario: ... //inside a class //function should accept a callback function as parameter refreshConnection(callback?: Function) { //do something //then ca ...

How do I insert a new column into the result set of a query in Prisma?

Imagine a scenario where there are two tables: User, which has fields for name and Id, and Post, which has fields for name and content. These tables are connected through a many-to-many relationship (meaning one post can have multiple users/authors and eac ...

I'm trying to access the login page, but I'm facing the challenge of doing so without

Is there a way to consistently monitor the presence of an internet connection without having to subscribe to network changes? My Question: Upon launching the app, I need to verify internet connectivity. If it is unavailable, I want to display a notificati ...

How can I incorporate static content files bundled with my JSON object into the API response in Nest.js?

Within my Nest.js API, there is a GET endpoint that needs to retrieve a database row along with up to 6 image files (base64 encoded) in the response. Currently, I am achieving this by extracting unique file names stored in 6 columns of the database and th ...

Angular Forms testing with Karma Unit Testing is throwing the following error message: ""

Here is a test case scenario: fit('When the Address field is left blank, it should be marked as Invalid', () => { component.basicBookFormGroup.patchValue({ bookName: 'My Site Name', bookOrg: 'Org ...

Angular2 Navigation Menu

I have a side bar and I want its children to appear when the user clicks on the parent. For example, clicking on LinkTest should display its corresponding content as block. You can check out the Angular and Typescript code snippet at this link: http://jsfi ...

Testing an Angular component using Jasmine within a project with multiple module files

Struggling to troubleshoot an issue I'm facing with my testing setup. The service tests that rely solely on the httpclient are running smoothly. However, when attempting to test a component with dependencies, errors start popping up without even execu ...

Tips for marking a p-checkbox as selected and saving the chosen item to a list

Here is a sample list: rows: any[] = [ {"id":"1721079361", "type":"0002", "number":"2100074912","checked":true}, {"id":"1721079365", "type":"0003", "number":"2100074913","checked":false}, {"id":"1721079364", "type":"0004", "number":"2100074914"," ...

Angular binding data property for displaying Twitter timelines using ngx-twitter-timeline

I've been struggling to set the data property of ngx-twitter-timeline programmatically. Below is the code snippet I am working with: <ngx-twitter-timeline [data]="{sourceType: 'url', url: 'https://twitter.c ...