Angular 2 encounters issues with *ngFor functionality

I am currently experiencing some difficulties while trying to use *ngFor to access an array of objects in Angular 2. When I define the array like this:

     employees=[ 
        {name:'a',age:'25'},
        {name:'b',age:'35'}
        ];

In my HTML template file, I have implemented *ngFor statements as follows:

        <ul>
         <li *ngFor="let employee of employees ; let i = index;">
           {{name}}
        </li>
       </ul>

However, upon checking the browser console, it is showing errors similar to the following (sample plunker available at http://plnkr.co/edit/0cBHaDM1mHvMf38NtQ7X?p=preview):

Error: Uncaught (in promise): Error: Error in :0:0 caused by: Array[2] is not a constructor TypeError: Array[2] is not a constructor at new AppComponent () at new Wrapper_AppComponent

As a newcomer to Angular 2, any guidance or support on resolving this issue would be highly appreciated.

Answer №1

Errors

  1. The markup in index.html was used incorrectly.
  2. employees= new Array[2]; is not the correct way to initialize an Array.
  3. names = new Array('qw','er'); is invalid.
  4. Values were not assigned using a constructor (which is considered bad practice).

To fix your code, it should look like this:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>Hellotest {{name}}</h1>
  <ul>
         <li *ngFor="let name of names ; let j = index;">
           {{name}}
           </li>
       </ul>
        <ul>
         <li *ngFor="let employee of employees ; let i = index;">
           {{employee.name}}
        </li>
       </ul>
       `
})
export class AppComponent { 
  name = 'Angular';
  employees= new Array();
  names = new Array();
  constructor(){
    this.employees=[ 
      {name:'a',age:'25'},
      {name:'b',age:'35'}
    ];
  
    this.names=['qw','er'];
    console.log(this.employees);
    console.log(this.names);
  }
}

Plunker with Updates

If you prefer not to use a constructor, declare variables like this:

name = 'Angular';
employees:any[]= [ 
  {name:'a',age:'25'},
  {name:'b',age:'35'}
];
names:Array<string> = ['qw','er'];

Plunker without Constructor

Answer №2

Kindly update your design to the following:

<ul>
   <li *ngFor="let employee of employees ; let i = index;">
      {{employee.name}}
   </li>
</ul>

The 'employee' variable represents each element in your array. To retrieve the name property for each object, you will need to access it accordingly.

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

Is there a way to make Typescript accept dot notation?

Is there a way to suppress the compile time error in Typescript when using dot notation to access a property that the compiler doesn't know about? Even though using bracket notation works, dot notation would be much more readable in my specific case. ...

Components in Angular do not refresh after using router.navigate

I currently have two main components in my Angular project: users.components.ts and register.components.ts. The users.components.ts displays a table of users, while the register.components.ts is where users can be added or edited. After making changes to ...

Retrieve values of properties from an array

How can I retrieve property values from an array? const d = [{id: 'Cat'}, {id: 'Dog'}] type ids = ??? //place code here, type should be 'Cat' | 'Dog' (It would also be acceptable if it creates a const enum) ...

Is there a way to specify the login response details when making an Angular API request?

I am currently using Angular to connect to my backend login service. However, I am facing an issue with setting the popup message when the username or password is incorrect. I want to display the detailed message from the API on my login page when any erro ...

Steps for numbering a list with multiple ngfors within a div using Angular

How can I ensure that multiple ngfors output an undefined number of results listed in a specific format with incremental numbering? EXPECTED OUTPUT: 1. Object 1 News: Object 1 Stuff 2. Object 1 News: Object 1 Stuff 3. Object 1 News: Object 1 Stuff ...

Passing HTML content to an ng-bootstrap modal in Angular 2+

My modal setup in the Component Library looks like this. Keep in mind, I am working within a Component Library, not just the application. Within my Component Library... The template is as follows: <div class="modal-header"> <h4 class="mt- ...

send information from a service's observable method to an unrelated component

service.ts @Injectable({ providedIn:'root' }) export class textAppService{ constructor(private http: HttpClient){} getPersonDetail(id:any):Observable<any>{ return id? this.http.post(ur;, {id:id}):of(new personDetails()); } } ...

What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggl ...

Having trouble with Nestjs Global Validation Pipe when parsing Boolean query parameters?

Within this controller, I am attempting to pass a boolean parameter in the GET call. @Controller('tests') export class TestController { constructor(private readonly testService: TestService) {} @Get() async getTests(@Query() params: ...

Extract the JSON array data from the Service and process it within the Component

When passing a response from the Service to the Component for display on the UI, each value needs to be parsed and stored in a variable. This can be achieved by extracting values such as profileId, profileName, regionName, etc. from the response. [{"profi ...

Ways to access details on the rejection process within a Prisma.$transaction

I am facing an issue with my database and updating student grades using Prisma transactions. When any ID is not found in the database, the transaction fails without indicating which record caused the error. I want to be able to throw a custom error that s ...

What is the timing for the execution of top-level non-export code in TypeScript?

I am currently puzzled about the execution of code in files. Let's say we have a file1.ts with the following content: export interface myInterface {} export function myFunction() {} export const myConst: {} // ... and more exports // top-level non- ...

Changes are made to the Angular template-driven form after certain controls have been added or removed

Within a fieldset, there exists a flexible number of 'select' drop down lists, accompanied by a button after each one (except the last one) to remove it. Upon selecting an option from the last select control, a new select control is dynamically a ...

Struggling to access the html elements within a component once the ng2 page has finished loading?

I am working on a web app that utilizes ng2-smart-table and I want to hide all cells within the table. However, when attempting to retrieve all the cells using document.getElementsByTagName("td") in the ngAfterViewInit() lifecycle hook, I noticed that the ...

What sets apart `const [a, b, c] = array;` from `const {a, b, c} = array;`?

let [x, y, z] = arr; let {x, y, z} = obj; Q: Can you explain the distinction between these two declarations? ...

What is the suggested method for supplying optional parameters to a callback as outlined in the Typescript documentation?

While going through the do's and don'ts section of the Typescript documentation, I came across a guideline regarding passing optional parameters to a callback function. The example provided was: /* WRONG */ interface Fetcher { getObject(done: ( ...

Ionic 4 and RxJS 6: Issue with Ionic-native HTTP get method not fetching data as expected

Currently, I am in the process of transitioning from using the angular HttpClient Module to the ionic-native HTTP Module. This switch is necessary because I have encountered difficulties accessing a third-party API using the standard HttpClient Module. To ...

In search of assistance with implementing Google Maps navigation into an Ionic 2 application

Incorporating external Google Maps navigation with ride distance and time is my goal. I am utilizing a method from phonegap-launch-navigator to achieve this. Here is the code for the method: navigate() { let options: LaunchNavigatorOptions = { s ...

Encountering a duplication issue when redirecting components in Angular2/TypeScript using navigateByUrl

Seeking guidance on implementing the login function where the current component redirects to another one upon clicking the login button. Below are my .ts and .html files: login.component.ts login.component.html The issue arises when using npm start for ...

Can someone show me how to handle a GET response in Angular 8?

I'm working on a .Net Core API that returns a response object with data and total pages. The data is an IEnumerable of orders, while the total pages is an integer value. var response = new { Data = data, ...