Tips for parsing data arrays in HTML templates

I have three variables and I created an array where I pushed all these three variables in.

In my HTML template, I am using a table. I tried using *ngFor but it is not working, and also attempted string interpolation which also did not work.

Currently, I am encountering an error "<--cannot read property "title" of undefined-->".

The data in my console looks like this....

array of data
(3)[{...}{...}{...}]
0:{key:"-LtZprPfMtDgzuxmaI5o"}
1:{price:1}
2:{title:"title1"}

array of data
(3)[{...}{...}{...}]
0:{key:"-LtcY8_6dd8fzibK9EYV"}
1:{price:2}
2:{title:"title2"}

array of data
(3)[{...}{...}{...}]
0:{key:"-LtcZF9NHknDZ0OcKzHg"}
1:{price:3}
2:{title:"title3"}

Below is the content from my product.component.ts file:

import { ProductsService } from './../../products.service';
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
  constructor(
    private products:ProductsService,
    private db : AngularFireDatabase
    ) { 
    products.getAll().on('child_added',function(c){
        let data = c.val();
        let key = c.key;
        let price = data.price;
        let title = data.title;
        let array=[];
        array.push({"key":key});
        array.push({"title":title});
        array.push({"price":price});
        console.log('array of data',array);
    })    
  }
}

And here is my admin-products.component.html:

<table class="table">
    <thead>
        <th>Title</th>
        <th>Price</th>
        <th></th>
    </thead>
    <tbody *ngFor="let p of array">
        <td>{{p.title}}</td>
        <td>{{p.price}}</td>
        <td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
    </tbody>
</table>

Answer №1

Based on the structure of your html code, it seems like you require an array of objects. Here is an example:

array = [
    {key: 'key1', title: 'title 1', price: 10},
    {key: 'key2', title: 'title 2', price: 10},
    {key: 'key3', title: 'title 3', price: 10}
]

If my understanding is correct, there are a few issues to address.

  1. The way the array is constructed is incorrect.
  2. Your array variable is currently local. It needs to be made public for access from within the html.
  3. In the html, you are attempting to iterate over the array but each iteration assigns data to a local variable 'p' (utilizing *ngFor="let p of array")

To resolve this, update your code as follows

import { ProductsService } from './../../products.service';
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
  array: any = [];
  constructor(
    private products:ProductsService,
    private db : AngularFireDatabase
    ) { 
    products.getAll().on('child_added',function(c){
        let data = c.val();
        let key = c.key;
        let price = data.price;
        let title = data.title;
        this.array.push({"key":key, "title":title, "price":price });
        console.log('array of data', this.array);
    })    
  }
}

Additionally, modify your html code to match this format,

<table class="table">
    <thead>
        <th>Title</th>
        <th>Price</th>
        <th></th>
    </thead>
    <tbody *ngFor="let p of array">
        <td>{{p.title}}</td>
        <td>{{p.price}}</td>
        <td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
    </tbody>
</table>

Answer №2

Revise this:

    <tbody *ngFor="let p of array">
        <td>{{array.title}}</td>
        <td>{{array.price}}</td>

to this:

    <tbody *ngFor="let p of array">
        <td>{{p.title}}</td>
        <td>{{p.price}}</td>

This code snippet involves an array of objects, thus necessitating the utilization of ngFor to iterate within the array and accessing attribute values using the variable p.

Answer №3

Check out this alternative solution:

  • Try implementing the loop in tr rather than td
  • Replace {{array.title}} with {{p.title}}
  • Ensure that array is declared as a global variable

.html

<tbody>
    <tr *ngFor="let p of array">
        <td>{{p.title}}</td>
        <td>{{p.price}}</td>
        <td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
    </tr>
</tbody>

.ts

export class AdminProductsComponent{
     array:any[] = [];
     products.getAll().on('child_added',function(c){
            let data = c.val();
            let key = c.key;
            let price = data.price;
            let title = data.title;
            this.array=[];
            this.array.push({"key":key});
            this.array.push({"title":title});
            this.array.push({"price":price});
            console.log('array of data',this.array);
        })  
}

Answer №4

In order to access the array variable in your template, you need to change it from a local variable inside the callback to a member of your component.

export class AdminProductsComponent{
  array: any[] = [];

  constructor(
    private products:ProductsService,
    private db : AngularFireDatabase
    ) { 
    products.getAll().on('child_added', c => {
        let data = c.val();
        let key = c.key;
        let price = data.price;
        let title = data.title;
        // Consider pushing one item per product into the array
        this.array.push({ key, title, price });
    })
  }
}

Template:

<tbody>
  <tr *ngFor="let p of array">
    <td>{{p.title}}</td>
  </tr>
</tbody>

Answer №5

Create a component with an array property that stores objects being passed into it. Utilize Arrow functions for callback functions to maintain the desired context of the component.

import { ProductService } from './../../product.service';
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
  // Array property declaration
  public itemsArray = [];

  constructor(
    private products: ProductService,
    private db: AngularFireDatabase
  ) { 
    products.getAll().on('child_added', (c) => {
      let data = c.val();
      let key = c.key;
      let price = data.price;
      let title = data.title;
      this.itemsArray.push({key, title, price});
    })    
  }
}

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

Component's mocking service is being ignored

I am currently exploring how to simulate a service (specifically one that makes http calls) in order to test a component. @Component({ selector: 'ub-funding-plan', templateUrl: './funding-plan.component.html', styleUrls: ['. ...

Preventing an infinite re-render loop caused by event listeners in React

One functional component is causing me some trouble: export default function Nav({photo}) { const [isOpen, setIsOpen] = useState(false) const [width, setWidth] = useState(window.innerWidth); const breakpoint = 768; useEffect(() => { ...

Rails 7 is missing the Toast element from Bootstrap 5

Having some trouble with implementing Bootstrap 5 Toast in Rails 7 for flash messages. Here is the code I am currently using: # application.html.erb <head> ... <%= javascript_importmap_tags %> <script> const toastElList = document.que ...

Is it not possible to change node labels in D3.js after clicking on a node?

After being inspired by this link, I successfully created a basic network visualization app using D3.js. The app reads node names from a textarea on an HTML page and then constructs a network where all nodes are interconnected. All the relevant code can ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

When utilizing Ionic with Angular, it is difficult to access the hardware back button on mobile devices that have buttons located within the display/screen

When trying to access the hardware back button in my app, I encountered an issue where I couldn't produce an alert message to the user before the app closed. After posting a question on Stack Overflow (link of the question) and receiving help from the ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Dialog component from HeadlessUI doesn't support the Transition feature

Currently working with Next.JS version 14.1.3 I recently integrated the <Dialog> component from HeadlessUI and configured TailwindCSS. However, I encountered an issue where the Modal window doesn't have any transition effects even though I foll ...

I am currently in the process of verifying email addresses

I attempted to validate multiple email addresses from a txt file and then save the valid emails to another txt file using nodejs. Unfortunately, it did not work as expected. Despite successfully reading the file, all emails were deemed invalid, even though ...

What is the best way to update the innerHTML of a date input to reflect the current value entered by the user?

Currently, my task involves extracting data from a table by obtaining the innerHTML of each row. The table contains date inputs that can be manually adjusted or generated automatically. However, the innerHTML does not update accordingly. Thus, when exporti ...

Is it really impossible to post complex JSON parameters with Restangular?

Is it possible to send a complex JSON object to a PUT route using Restangular? Restangular.one('model3ds', model.uuid).put( api_key: "blabla" model3d: { is_public: true } ) However, the data sent by Restangular appears as: ...

Performing an Ajax request to submit a form without the need to reload the page in MVC

I am looking for assistance with submitting a form from an MVC view without refreshing the page. However, it seems that my AJAX code below is not functioning properly: //here is ajax call function AjaxCallAndShowMessage(btnClick) { $('form').s ...

Utilizing dropdown list values within the context of $.getJSON: A practical guide

This is the script that I have written. $.getJSON("Employee.js", function (data) { var sample = data.one;alert(sample) }); Below you can see the contents of the Employee.js file: var sample={ "one":"Manager","two":"Sr.Eng","three":"Eng" } I am ...

What's the Hold-Up with IntersectionObserver in Brackets?

As a novice in the world of web development, I have been utilizing Brackets as my main tool. Recently, I've encountered a few hurdles specifically related to javascript. One issue I'm facing is trying to implement lazy loading on a div containing ...

Running JavaScript code when the route changes in Angular 6

Currently, I am in the process of upgrading a website that was originally developed using vanilla JS and JQuery to a new UI built with Angular and typescript. Our site also utilizes piwik for monitoring client activity, and the piwik module was created i ...

Issue encountered with ng-include compatibility in Angular 5

Just getting started with Angular and working on a small test project using Angular 5 and Visual Code. I'm attempting to use ng-include but the template is not displaying. src add-device add-device.component.html add-device.com ...

The error message "No native build was found for M2 MacBook" appeared while using npm with Node

I encountered this issue while working on my M2 MacBook, which ran smoothly on my older Intel MacBook. Any insights on what might be causing the problem? Using bun, but even running npm run dev (node 18) results in the same error. The same error has also ...

Creating a sidebar with child elements in Vitepress: A beginner's guide

I'm having trouble displaying my folder tree in the sidebar. When I click on a parent element like Group, the children elements are not showing up as expected. https://i.sstatic.net/kdc98.png One strange thing is that the Group elements do not have ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...