Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format.

Below is the TypeScript code snippet that outlines the structure of the student data:

    export interface studentData{
      ID : number;
      Name :string;
      Class : string;
      Languages: string;
    }
    
    const STUDENT_DATA: studentData[] = 
    [
     {
      ID : 1
      Name: "Amy",
      Class: "Grade1",
      Languages: "Java, .net, Python"
     },
     {
      ID : 2
      Name: "John",
      Class: "Grade2",
      Languages: "Kotlin, Java, Typescript"
     },
     {
      ID: 3
      Name: "Shawn",
      Class: "Grade3",
      Languages: "Javascript, C++, Perl"
     },
    ]
export class StudentDataComponent{
       languages : string[] = [];
    for (let i=0; i <= STUDENT_DATA.length - 1 ; i++)
     {
       this.languages = STUDENT_DATA[i].Languages.split(",");
     }
}

I have attempted to separate the "Languages" into an array and plan to utilize it for display purposes using ngFor directive.

languages : string[] = [];
for (let i=0; i <= STUDENT_DATA.length - 1 ; i++)
 {
   this.languages = STUDENT_DATA[i].Languages.split(",");
 }

In my efforts to display the information using mat-chip-list, I encountered a challenge where it only shows ID 3 languages for all IDs.

<mat-chip-list>
   <mat-chip *ngFor = "let lang of languages>
         {{lang}}
   </mat-chip>
</mat-chip-list>

If anyone has suggestions on how to correctly read the languages from the JSON value and properly display them on the screen, your assistance would be greatly appreciated.

Answer №1

If you're looking to iterate through the languages string for each student in the loop, you can utilize your split() function within a nested ngFor loop, like this:

<div *ngFor="let student of STUDENT_DATA">
 <!-- .... -->
  <mat-chip-list>
     <mat-chip *ngFor="let lang of student.languages.split(',')">
         {{lang}}
     </mat-chip>
  </mat-chip-list>
</div>

Answer №2

"the issue lies in displaying only 3 languages for all students"

this occurs because the variable this.language is being overwritten with each iteration, ultimately showing only the last language. There is no distinct language array for each student.

A more effective solution could be to include a new property on each student object. For example:

this.students = STUDENT_DATA.map(s => {
    ...s,
    LanguageArray: s.Language.split(",").map(l => l.trim())
});

This way, the language array becomes part of the student data that can then be accessed when iterating through the students list outside of the mat-chip. You could use

*ngFor="let lang of student.LanguageArray
within your
*ngFor="let student of students"

Answer №3

Your current code is causing the language variable to be overwritten in each iteration. To fix this, we need to modify the type of languages and also include an index in the languages variable:

let languages: string[][] = [];

for (let i = 0; i <= STUDENT_DATA.length - 1; i++) {
    languages[i] = STUDENT_DATA[i].Languages.split(",");
}

You can update your code to something like this:

<student-element *ngFor="let student of STUDENT_DATA; index as i">
// Element code here
<mat-chip-list>
  <mat-chip *ngFor = "let lang of languages[i]">
    {{lang}}
  </mat-chip>
</mat-chip-list>
</student-element>

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

Updating the jQuery datatable with new data after a page switch or another action

One of the features on my page is a jQuery datatable that I populate with data using the following script: $(document).ready(function () { var dataTable; $(document).on("click", ".myBtnClass", function () { if (dataTable != null) ...

What is the best way to distinguish between administrators and regular users in an Angular project?

I am embarking on a project using Angular and I plan to incorporate both an admin and a user section within it. Is there a way to effectively separate the admin area from the user area in Angular? Additionally, how can I differentiate the style files for ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

How can you display varying information based on a dropdown selection using Material-UI's Select component?

By default, the Select component is populated with the correct data. However, I am facing an issue where selecting the "InReview" option should display the options inside the statusArr and remove the previous ones. Thank you in advance for your help. Her ...

TypeError: "Table" has not been declared

This is my first experience with the script editor. I have been given the task of creating a pivot table for Google Sheets using a script. // This script creates a pivot table in Google Sheets function createPivotTable() { var ss = SpreadsheetApp.getAc ...

React fails to display the content

Starting my React journey with Webpack configuration. Followed all steps meticulously. No error messages in console or browser, but the desired h1 element is not showing up. Aware that React version is 18, yet working with version 17. App.jsx import Reac ...

Developing the headers for a service using React.js

As someone new to ReactJs, I'm curious about the various methods we can use to include Headers in our service Url before making a call. While I'm familiar with how GET/POST Calls are made in angular Js after including headers, I'd like to l ...

Jquery is failing to handle multiple inputs

I am currently working on a system that can handle multiple Yes/No questions. However, every time I try to submit the form, I encounter an error in the console that I cannot identify, and no data is returned from the query. Previously, I used an Array to s ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

developing versatile paths with Node.js

app.js // Including Routes require("./routes")(app); router folder index.js module.exports = function (app) { app.use("/", require("./all_routes")); } all_routes.js var express = require("express"); var route ...

Discover the best way to showcase items within an arrayList using dual CSS styles!

I'm currently working on a project that involves an arrayList with two names: Bob and Steve. I have the requirement to display them in different colors, where Bob should be displayed in green and Steve in red. Component.CSS .Bob{ font-weight:bold; ...

Using Javascript to apply styling only to the first class element in the document

I am facing a challenge with styling programmatically generated classes and inputs. Here is an example of the structure: <div class="inputHolder"> <input type="button" class="inputclss" value="1"> </ ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Issue with updating required Node.js/Express modules using Chokidar?

After browsing through numerous questions and answers regarding chokidar, I am still struggling with an issue. It would be greatly appreciated if someone could help debug my particular code snippet. The Express node app I am working on is running at local ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

Establishing Redux States within the Provider (error: Provider encountering useMemo issue)

Exploring redux for state management has been a new journey for me. I am hoping it will help reduce API calls and increase speed, but I've hit a roadblock with an error that I can't seem to figure out. To troubleshoot, I created a simplified vers ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

Accessing User Input Data with JQuery

Can someone help me figure out how to store the input value from a Materialize select form in HTML using a variable in javascript/jquery? Here is the HTML code for the form: <div class="input-field col s12"> <select> <option va ...

Combining and linking 3 RxJS Observables in TypeScript and Angular 4 without nesting to achieve dependencies in the result

I have 3 observables that need to be chained together, with the result from the first one used in the other 2. They must run sequentially and each one should wait for the previous one to complete before starting. Is there a way to chain them without nestin ...

How can Vue.js pass an array from a child component to its parent component?

I'm currently developing a contact book app and I have created a modal within a child component that contains a form with several input fields. My goal is to utilize the values entered in the form and add them to the parent component. I have successfu ...