Using the length of an array as an iterator within a nested ngFor loop in Angular 9

I am looping through an array of objects where each object contains another array of objects with attributes like "name" and "id". The length of this array of objects (noticias) varies.

I am struggling to display these values and have only managed to access and display them by hardcoding the "X" as shown below.

<div *ngFor="let c of DATA; let i = index;">
  {{i}}{{c.name}}   

  <div *ngFor="let novedad of DATA; let i2 = index; ">
    <div *ngIf="i2 === i">
     {{novedad.noticias[0][X].name | json}}    --> HERE      
    </div>

  </div>
</div>

The DATA array is generated by a service that makes a series of HTTP calls to form this array.

Is there a way to loop through and display the values like

{{novedad.noticias[0][LOOP THROUGH THE LENGTH OF EACH OBJECT].name | json}}
?

I hope my question is clear. Thank you in advance!

JSON object:

    [
  {
    "id": 6,
    "name": "Encantamientos",
    "forumid": 6,
    "courseid": 6,
    "type": "news",
    "noticias": [
      "Este curso no tiene novedades"
    ]
  },
  {
    "id": 5,
    "name": "Historia de la magia",
    "forumid": 5,
    "courseid": 5,
    "type": "news",
    "noticias": [
      [
        {
          "id": 9,
          "name": "aviso 1",
          "groupid": -1,
          "timemodified": 1585598111,
          "usermodified": 3,
          ...
        }
      ]
    ]
  },
  {
    "id": 2,
    "name": "Difusión ",
    "forumid": 1,
    "courseid": 2,
    "type": "news",
    "noticias": [
      [
        {
          "id": 8,
          "name": "tema difusin 3",
          "groupid": -1,
          "timemodified": 1585595618,
          "usermodified": 3,
          ...
        },
        ...
      ]
    ]
  },
  {
    "id": 4,
    "name": "Quimica",
    "forumid": 3,
    "courseid": 4,
    "type": "news",
    "noticias": [
      [
        {
          "id": 7,
          "name": "aviso quimica 3",
          "groupid": -1,
          "timemodified": 1585324962,
          "usermodified": 3,
          ...
        },
        ...
      ]
    ]
  }
]

Answer №1

It seems like you might be confused, but all you need to do is:

<div *ngFor="let c of DATA; let i = index;">
  {{i}}{{c.name}}   

  <ng-container *ngFor="let inner of c.noticias">
    <div *ngFor="let novedad of inner">
      {{novedad.name | json}}      
    </div>
  </ng-container>
</div>

ngFor your DATA array, then within each of those, ngFor over the noticias array, and then once again over the inner as it's an array of arrays.

Answer №2

<div *ngFor="let category of categories; let index = idx;">
  {{index}}{{category.name}}   

  <div *ngFor="let item of category.items; let idx2 = index;">
    <div *ngIf="idx2 === index">
     {{item.news[idx2].name | json}}    --> HERE      
    </div>

  </div>
</div>

Based on the structure provided, this is the expected format. However, adjustments may be needed based on the response data.

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

Understanding the fundamentals of event handling in JavaScript

Is there a way to access the object that called the event handler within the event handler function itself? For example: marker.on('dragend', onDragEnd); In this case, marker is the object that triggers the ondragEnd function on the Dragend eve ...

How to refresh an Observable in Angular 2

Description: Presently, I am utilizing Angular2 (now updated to Angular4). In my component's constructor, I am subscribing to a service using the code: this.policyService.getBaseCommission().subscribe(response => response). The data obtained from ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

What is the best way to remove a property from an object in React if the key's value is set to false?

I'm currently working on a form component and I've encountered an issue. Whenever I submit the form, it returns an object with various fields such as email, fieldName1, fieldName2, first_name, last_name, and organization. Some of these fields are ...

Save the result of a terminal command into an sqlite database

When I run a particular shell command in node js, the output is displayed on the console. Is there a method to store this output in a variable so that it can be POSTed to an Sqlite database? const shell = require('shelljs'); shell.exec('a ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...

Having trouble with validation messages not displaying correctly in Angular after removing a value. What is the correct approach to fix this issue

I've encountered an issue with Angular validation where it's triggering validation on page load, which is not desired. Additionally, when I enter a value, the validation message disappears, but if I return to the textbox and delete the input, the ...

Initiating the accordion feature requires two clicks and triggers an rotation of the icon

I managed to integrate some code I discovered for a FAQ accordion on my website. I am struggling with getting the title to expand with just 1 click instead of 2. Additionally, I would like the icon to rotate when expanding/collapsing, not just on hover. Be ...

In Rails 3, you can utilize JavaScript to submit a form_tag remotely, however ensure that it submits as

I am trying to implement a form_tag in rails 3 that can be submitted using ajax instead of html through javascript. Despite setting the form to submit as javascript, it still submits as html when clicking the submit button. - form_tag({:controller => " ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...

Transferring query parameters to a new page using the POST method in a Node JS and Express application

I'm experiencing an issue where I need to pass the same id through multiple consecutive web pages using query parameters. While transferring the param with GET routes works fine, I encounter a problem on the third page which has a short form and uses ...

A guide to implementing infinite scrolling with vue-infinite-loading in Nuxt.js (Vue.js)

Currently, I am working on developing a web application using Nuxt.js (Vue.js). Initially, to set up the project, I used the command: vue init nuxt/express MyProject ~page/help.vue <template> <div> <p v-for="item in list"> ...

Is there a way to invoke JavaScript functions from external files in an EJS template?

I've got this new Ship file to add. The script that populates the fleet dropdown menu is working perfectly: new.ejs file: <% include ../partials/header %> <div class="container"> <div class="row"> <h1 style="text-al ...

What is the best way to utilize the history prop in conjunction with other props?

I am currently using react-router-dom along with react. My goal is to include additional props along with the history prop import React from 'react'; function MyComponent({ history }) { function redirect() { history.push('/path&ap ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Check to see if two sets of coordinates fall within the specified radius

I'm currently working on analyzing the collision data for major intersections in my city by aggregating it with the location information. My main goal is to determine the number of accidents that occurred within a 20-meter radius of each intersection. ...

Loading an Angular component using either its name (string) or selector (string) in Angular version 12 and above

I have successfully implemented a feature in my Angular 12 project where I pass the component name in a div tag and it automatically gets rendered. You can see the working example on Stackblitz by following this link: https://stackblitz.com/edit/angular-e ...

Transforming Ember's ajax query string

Using ember-model, I am making a request like this: App.Video.find({'sort':'createdAt+asc'}); to retrieve a sorted list of videos. This should result in the following request: http://localhost:1337/api/v1/videos?sort=createdAt+asc How ...

Issues encountered when trying to modify the Content-Type of POST requests using ngResource versions 1.0.6 and 1.1.4

Despite numerous attempts and trying various solutions found online, I am still unable to solve this issue. Similar questions have been asked in the following places: How to specify headers parameter for custom Angular $resource action How can I post da ...