When working with Angular 2, it is important to note that the NgFor directive only supports binding to Iterables like Arrays. If you encounter an error message stating "Cannot find a differ supporting object '[object Object]' of type 'leaveType

After an extensive search and exploration for a solution to my problem, I found one, but unfortunately it didn't work as expected. The issue at hand involves displaying static data/list in dropdown options using TypeScript. Currently, I am working with an array of objects called leaveType. However, when attempting this, I encountered the following error:

ORIGINAL EXCEPTION: Cannot find a differ supporting object '[object Object]' of type 'leaveType'. NgFor only supports binding to Iterables such as Arrays.

I would greatly appreciate any guidance on where I may be going wrong.

Here is my code snippet:

team-component.ts

import { Component, OnInit, HostBinding                       } from '@angular/core';
import { FormGroup, FormBuilder, Validators      } from '@angular/forms';
import { IMyOptions, IMyDateModel                } from 'mydatepicker';
import { CONSTANT                                } from '../../constants/dash-constant';
import { TeamService                             } from '../../services/team-component.service';
import { slideInDownAnimation                    } from '../../animations/animations'

@Component({
  selector: 'team-component',
  templateUrl: `../app/modules/dashboard/dashComponents/teamComponents/team.component.html`,
  animations: [slideInDownAnimation],

})

export class TeamComponent implements OnInit {
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display') display = 'block';
  @HostBinding('style.position') position = 'absolute';

  constructor(private teamService: TeamService) {
  }


  ngOnInit() {
     this.leaveType.push({ id: 0, type: 'Earned Leave' });
     console.log( this.leaveType);
    }
     private leaveType:any=[];
     public leave:any= { "employee": null, "from": null, "to": null,'leaveType':null };

 }

team-component.html:

 <div class="row">
            <h4>Leave Type:</h4>
            <div class="form-group  col-md-10">
              <select id="leaveType" class="form-control" name="leaveType" [(ngModel)]="leave.leaveType" required #leaveType="ngModel">
          <option *ngFor="let p of leaveType" [value]="p.type">{{p.type}}</option>
        </select>
              <div *ngIf="leaveType.errors && leaveType.touched" class="alert alert-danger">
                <div [hidden]="!leaveType.errors.required && leaveformSubmitted">Leave type is required</div>
              </div>
            </div>
          </div>

Answer №1

There seems to be a name clash in your html code.

  <select id="leaveType" class="form-control" name="leaveType" [(ngModel)]="leave.leaveType" required #leaveType="ngModel">

The select element has both attributes name and id set as leaveType, which could lead to ambiguity when using it with *ngFor directive.

Answer №2

It is necessary to define the 'leaveType' variable as an array data type. Here is an example:

....
private leaveType: any[] = [];
public leave:any= { "employee": null, "from": null, "to": null,'leaveType':[] };
....

Answer №3

leaveType should be defined as an empty array:

declare leaveType as an array with no initial values:
private leaveType:any[] = [];

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

Tips for accessing the callback parameter in the validateFields method of antd form

Here is a question about typing the callback parameters for form.validateFields in Ant Design when using the Form HOC. // App.tsx import { FormComponentProps } from 'antd/lib/form'; interface IProps extends FormComponentProps { ... } class App ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

What could be causing me to lose my login information on my React application?

I have a reactjs application that utilizes a django backend for handling authentication. Below is a snippet of my Typescript code from the App.tsx file in my react app: import React, {useState, useEffect} from 'react'; import { BrowserRouter as ...

Angular frontend failing to send authorization cookie for cross-origin requests, despite using withCredentials

Today, I've been facing a persistent issue that I just can't seem to figure out. I have my Angular frontend running on localhost:4200 and a Spring Boot backend on localhost:8080. When I call the localhost:8080/api/login endpoint from my Angular ...

A guide on integrating mat-select into Angular input fields

I've been trying to implement a mat-select dropdown on my input field, but for some reason, when I click on the arrow, nothing happens and the list doesn't show up. Usually, with autocomplete, when a user starts typing, all the options are displ ...

Troubleshooting Angular: Dealing with Cross-Origin Resource Sharing (CORS) issue

I am currently facing an issue with posting data to elasticsearch from my service. The CORS policy is blocking the action and even after attempting to use a proxy script, the error persists. Can anyone offer assistance in resolving this? Here is the proxy ...

What are the best ways to quickly avoid changing routes in Angular?

My routing logic includes: this.route.paramMap .pipe(switchMap((parameters) => of(parameters))) .subscribe((params: Params) => { if (params.has("id")) { // Send request to server } if (params.has("block")) ...

Insert placeholder text without access to the input field

Is it possible to activate a placeholder in a component that is outside of the current context? For example: <foreign-component [config]="someConfig" placeholder="somePlaceholder"></foreign-component> The <foreign-compo ...

Executing an Observable function in Angular Typescript a single time

Within my Angular application, there exists a service responsible for retrieving data from a server. load.service.ts: load = new Observable(observer => { console.log('load function called'); // asynchronous tasks with time delay obser ...

The function is unable to access the 'FacebookAuthProvider' property as it is undefined

I'm having trouble using Angular Firebase to connect with Facebook. I keep encountering this error: AppComponent.html:2 ERROR TypeError: Cannot read property 'FacebookAuthProvider' of undefined at AuthService.signInWithFacebook (auth.servic ...

Error encountered in TypeScript when attempting to override a method: The distinction between Overriding and Overloading

In my Angular 9 application, I have two classes that I am using as services: class A and class B, where class B extends class A. class A{ exportToCSV(data: any[], headers: any[]){ .... } } class B extends A{ exportToCSV(data: any[], headers: ...

Return to the previous page with different query parameters, not the same one

When it comes to reverting state location back by 1 step in Angular, we can utilize something along the lines of this.location.back();. This method works well unless the system redirects to the same URL but with different query parameters. In such cases, ...

How can I access Angular in the console through devtools on Angular 8?

I'm currently using Angular 8 and I came across this outdated advice on how to test an AngularJS service from the console on Stack Overflow. Despite following the steps mentioned, I encountered some disappointing output. Angular is running in the dev ...

Building a search feature with a customized pipe in Angular

I attempted to create my own custom pipe in Angular 6 for filtering a list of campaigns using a search box. Strangely, I am having trouble getting the filter to work on the campaign list. Below is the code snippet that I have written. This is the implemen ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

Organizing data with JavaScript: Transforming a flat array into nested JSON structures

In my front-end TypeScript file, there is a list called poMonths: 0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"} 1: {id: 2, company ...

Verifying the Presence of an Image in the Public Directory of Next JS

My TypeScript Next.js project contains a large number of images in the public folder. I am wondering if there is a way to verify the existence of an image before utilizing the <Image /> component from next/image. I have managed to achieve this using ...

Create the HTTP POST request body using an object in readiness for submission

When sending the body of an http post request in Angular, I typically use the following approach: let requestBody: String = ""; //dataObject is the object containing form values to send for (let key in dataObject) { if (dataObject[key]) { ...

Ways to imitate an export default function

//CustomConfigurator.ts export default function customizeConfig(name: string): string { // add some custom logic here return output; } //CustomUtility.ts import customizeConfig from './CustomConfigurator'; export default class CustomUtility ...