Having trouble with Angular 4 data display? See how to fix a simple example that's

I can't seem to display my data correctly in Angular. When I try, all I get are empty bullet points and an error message that says "Cannot read property of 0 undefined." Even though the code appears to be correct, it's not functioning as expected. What could be causing this issue?

This is the code I am using:

a) Offer.ts

export class Offer
{
    constructor(
      public id      : number,
      public title   : string,
      public owner   : string,
      public productOffer    : [ {'id': number, 'name': string} ]) {}
}

b) offer.component.ts

<!-- language: lang-js -->
import { Component, OnInit } from '@angular/core';
import { Offer } from '/offer';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser"; 

 @Component({
  selector   : 'app-offers',
  templateUrl: './offers.html',
  styleUrls  : ['./offers.scss']
            })  

export class OffersComponent implements OnInit {
 public offers: Offer[];
  constructor() { 
    this.offers = [
      {
        id : 1,
        title : 'Offer 01',
        owner : 'Mr Owner',
        productOffer : [                                                 
           { id : 1, name: 'Soap'},
           { id : 2, name: 'Cover'},
                  ]
      },
      {
        id : 2,
        title : 'Offer 01',
        owner : 'Mr Owner2',
        productOffer : [                                                 
           { id : 1, name: 'Soap2'},
           { id : 2, name: 'Cover2'},
                  ]
              }];               
          }

         ngOnInit() {  } 

        }

c) offer.component.html

<ul ng-repeat="offer in offers">
        <li>example</li>
        <li><h1>{{ offer.owner }}</h1></li>
        <li>{{offer.title}}</li><br><br>
        <li><button>{{offer.id}}</button></li>
</ul>

d) I have also tried:

  <ul>
    <li>example</li>
    <li *ngFor="let offer of offers">{{ offer.owner }}</li>     
  </ul>

The result I am seeing with both methods is just empty bullet points.

Additionally, I'm encountering these errors:

https://i.sstatic.net/PRPjS.png

https://i.sstatic.net/l2ASd.png

If anyone can provide insight or assistance, I would greatly appreciate it. I've been trying to troubleshoot this for hours without success.

Answer №1

To correctly display your data in Angular, use *ngFor instead of ng-repeat as AngularJS syntax is different. Additionally, switch out in for of.

<ul *ngFor="let item of items">
     <li>example</li>
     <li><h1>{{ item.name }}</h1></li>
     <li>{{ item.description }}</li><br><br>
     <li><button>{{ item.id }}</button></li>
</ul>

Answer №2

When comparing AngularJS with Angular (starting from version 2 and now at version 5.2), the syntax for each differs:

<!-- AngularJS -->
<ul>
  <li ng-repeat="item in items">
    {{$index}} {{item}}
  </li>
</ul>

<!-- Angular -->
<ul>
  <li *ngFor="let item of items; let i = index">
    {{i}} {{item}}
  </li>
</ul>

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

A single image path utilized for both development and production stages during the Angular build process

I am struggling to determine the correct path for my images to work seamlessly on both development and production environments. Currently, I can only get them to display properly on my local development server. However, when I use the command ng build --pr ...

Angular Signal computation does not initiate a re-render

I am currently working on sorting an array of signals within my component. To achieve this, I have wrapped the array in a compute function that sorts it. Below is the relevant code snippet: In the Service file: private readonly _lobbies = signal<Lobby ...

how to retain the state value as a number and enable decimal input in a TextField component in React

Currently working on a project using React, Material UI, and TypeScript. I need to enable decimal values in a TextField while ensuring that my state value remains a number type instead of a string. export default function BasicTextFields() { const [value ...

Is there a way to merge my local store with Firestore using ngrx entity?

Currently, I'm facing a challenge while using NgRx and Firestore as I attempt to keep the local store in sync with a firestore collection. I have set up an observable that triggers when the firestore collection is updated. However, in my reducer, I am ...

Creating Angular components and attaching them to the body tag is a simple yet

My goal is to create a component at the root element of the page. I have come across some resources that are similar to what I need, but they use the DynamicComponentLoader which is now considered deprecated. public component: any; constructor( public ...

Running nestjs-console commands within an Angular/nx workspace environment can be easily achieved by following these steps

I have integrated a NestJS application within an Angular / Nx workspace environment. For running commands in the Nest application, I am utilizing nestjs-console (e.g., to load fixture data). As per the instructions in the nestjs-console documentation, th ...

Refining types in a series of statements

I'm attempting to merge a series of assertions in a safe manner without the need to individually call each one. For instance, consider the following code: type Base = { id: string, name?: string, age?: number }; type WithName = { name: string }; type ...

Angular - Issue with setting default value in a reusable FormGroup select component

My Angular reusable select component allows for the input of formControlName. This input is then used to render the select component, and the options are passed as child components and rendered inside <ng-content>. select.component.ts import {Compon ...

What is the best way to merge an array into a single object?

I have an array object structured like this. [ { "name": "name1", "type": "type1", "car": "car1", "speed": 1 }, { "name": &q ...

Inquiry on SSGHelpers and GetStaticProps functionality with parameterization

I am currently implementing createProxySSGHelpers to prefetch data using trpc in a project I'm developing, but I'm facing an issue where the id from the url params is returning as undefined even though it's visible in the url bar. Below is ...

Problem with Angular input field not updating after making an http request

After receiving a response from an http get request, I'm attempting to map the data with an input field but it's not working as expected. this.http.get<any>('https://localhost:9002/....../getEmail') .subscribe({ ...

What is the best way to maintain the routerLinkActive state when navigating to another component page that is related to the current page

Why does the navigation link become inactive when routing from myloans to syncmyloans? How can I maintain navigation activation when moving to related sub pages within the main navigation? Navigation <nav> <ul class="navbar-nav ml-auto&q ...

Retrieve the API output and save the information into an array

I am struggling with calling an API in my Angular application and extracting specific data from the JSON response to populate an array. Although I am able to retrieve the response, I am having trouble isolating a particular field and storing it in an array ...

The declared type 'never[]' cannot be assigned to type 'never'. This issue is identified as TS2322 when attempting to pass the value of ContextProvider using the createContext Hook

I'm encountering an issue trying to assign the state and setState to the value parameter of ContextProvider Here's the code snippet:- import React, { useState, createContext } from 'react'; import { makeStyles } from '@material-ui ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

What is the best way to save code snippets in Strapi for easy integration with SSG NextJS?

While I realize this may not be the typical scenario, please listen to my situation: I am using Strapi and creating components and collections. One of these collections needs to include code snippets (specifically typescript) that I have stored in a GitH ...

The name 'Map' cannot be located. Is it necessary to alter your target library?

After running the command tsc app.ts, an error occurs showing: Error TS2583: 'Map' is not recognized. Should the target library be changed? Consider updating the lib compiler option to es2015 or newer. I want the code to compile without any issu ...

Tips for incorporating a mail button to share html content within an Angular framework

We are in the process of developing a unique Angular application and have integrated the share-buttons component for users to easily share their referral codes. However, we have encountered an issue with the email button not being able to send HTML content ...

Specialized typescript function that is compatible with extended interfaces

Is there a way to create a versatile function that can be applied to any interface derived from a top-level interface? This function should take an unpersisted interface (without an id property) and return a persisted one (with an id property). The two ma ...

Tips for restricting a drag-drop container to only receive a single item in Angular Material's Drag-Drop functionality

Is there a way to restrict the drop container in @angular/cdk/drag-drop module (Angular Material Drag and Drop) to only accept one value instead of multiple values? I am working on a form where users can drag an image and drop it into a field that should o ...