Angular error with supporting element discrepancies

I've been working on an Angular project and I'm trying to show a filtered list of data on my UI from the main component.

Even after implementing the filter function, I'm struggling to save the filtered data in the same format as my original data.

Unfortunately, when trying to do so, I encounter this error:

"Cannot find a differ supporting object '[object Object]' of type 'Shubham Bhatt'. NgFor only supports binding to Iterables such as Arrays.

My goal is to have the filteredEmpData match the structure of empData.

I did some research and found a solution that involves converting the object into Arrays. However, I'm wondering if there's another way to achieve this.

P.S: Total beginner here.

Here's my progress so far:

    export class AppComponent {
  // tslint:disable-next-line:no-inferrable-types
  title: string = 'Birthday App';
  tDate: any = new Date();
  tMonth: number = this.tDate.getMonth() + 1;
  tDay: number = this.tDate.getDate();
  empData: IEmpdatatype[] = [
  {
    'name': 'Anurag Basu',
    'DOB': '1996-09-10',
    'email': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eecfff0faf1f3fbf3fff7f2def9f3fff7f2b0fdf1f3">[email protected]</a>',
    'imageLink': 'https://qph.fs.quoracdn.net/main-thumb-314460666-200-repbvxtqtsknkwpbemcejkxjnplkcmip.jpeg'
  },
  {
    'name': 'Shubham Bhatt',
    'DOB': '1996-06-26',
    'email': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8f9391998e9d9298939199919d9590bc9b919d9590d29f9391">[email protected]</a>',
    'imageLink': 'https://qph.fs.quoracdn.net/main-thumb-314460666-200-repbvxtqtsknkwpbemcejkxjnplkcmip.jpeg'
  }
];
filteredEmpData: IEmpdatatype = this.check();
check(): IEmpdatatype {
    // console.log(typeof(this.empData));
    // tslint:disable-next-line:prefer-const
    let monthStr: string = this.tMonth.toString();
    let dayStr: string = this.tDay.toString();
    if ( monthStr.length === 1 ) {
      monthStr = '0' + monthStr;
    }
    if ( dayStr.length === 1) {
      dayStr = '0' + dayStr;
    }
    for (let i = 0; i < this.empData.length; i++) {
      const DOBsplit: string[] = this.empData[i].DOB.split('-');
      if ( DOBsplit[1] === monthStr && DOBsplit[2] === dayStr) {
        this.filteredEmpData = this.empData[i];
      }
    }
    console.log(this.filteredEmpData);
    return this.filteredEmpData;
  }
}

App.component.html

<div class="thisMonth">
    <ul *ngFor='let filteredEmpD of filteredEmpData'>
      <li><span><img [src]='filteredEmpD.imageLink' id="img-round"></span><span>{{filteredEmpD.name}}</span><span>{{filteredEmpD.DOB}}</span><span><a type="button" href="mailto:{{filteredEmpD.email}}?Subject=Happy%20Birthday">Wishes</a></span></li>
    </ul>
  </div>

Answer №1

When looking at your method verify, it appears that you are making changes to the this.filteredEmployeeData. Instead of adding elements to it, you are assigning a specific index from the employeeData property. As a result, the filteredEmployeeData ends up being an object of type IEmployeeDataType rather than an array of IEmployeeDataType[].

To improve this, consider refactoring the verify method as shown below:

verify(): IEmployeeDataType[] {
    const results: IEmployeeDataType[] = [];
    let monthString: string = this.targetMonth.toString();
    let dayString: string = this.targetDay.toString();
    
    if (monthString.length === 1) {
      monthString = '0' + monthString;
    }
    
    if (dayString.length === 1) {
      dayString = '0' + dayString;
    }
    
    for (let j = 0; j < this.employeeData.length; j++) {
      const birthdaySplit: string[] = this.employeeData[j].birthDate.split('-');
      
      if (birthdaySplit[1] === monthString && birthdaySplit[2] === dayString) {
        // Adding matching data to results
        results.push(this.employeeData[j]);
      }
    }
    
    console.log(results);
    return results;
}

Answer №2

Instead of directly assigning the object to the filteredEmpData array, make sure to push the object into it.

Replace the following line:

this.filteredEmpData = this.empData[i];

With this:

this.filteredEmpData.push(this.empData[i]);

Also, don't forget to initialize the array before pushing any data into it. So, before the for loop begins, initialize it as:

this.filteredEmpData = [];

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

The functionality to subscribe in ts(6385) has been marked as

I am encountering an error message regarding the deprecation of the subscribe function in my code. The issue seems to be with the second part of the code for the getStarwarsHeroes function, where the .subscribe method is being deprecated. import { Injectab ...

Attempting to limit a TypeScript method to only accept and return objects, yet TypeScript is accepting other data types as well

Hey there! I'm facing a challenge with TypeScript where I'm trying to restrict the return type of a function passed as an argument to only allow objects ({x: 42}). Despite using extends object, it seems to allow anything. I've been strugglin ...

Bypass URL Routing for a specific route in Angular 8 and Apache

I currently have two Angular applications: the FrontEnd and Admin. Both of these are hosted on cPanel behind an Apache server. The website setup is as follows: mydomain.com/ ----> Frontend Angular Application mydomain.com/admin ----> Admin Angular ...

Error in Angular: A ReferenceError has occurred stating that the bootstrap is not defined

I'm having trouble understanding why the error persists even though I've declared Bootstrap and confirmed it's defined when debugging. Does anyone have any insights on why this might be happening? Could it be related to Bootstrap? Here is t ...

TypeScript, express framework, node-dev tool, and a personalized file type loader

Looking to create a node.js server with Express and TypeScript, while also wanting the ability to auto-restart or hot-reload during development as I make changes. Additionally, I need the capability to import custom file types. While Webpack can handle so ...

Unable to locate element within the HTML code in Angular

Despite using document.getElementByID, I am unable to retrieve the value of the list element in the HTML. The code shows that the element is undefined, even though it has the same id. Here is the snippet of code: fileupload.component.ts: ngOnInit() { ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

Setting up admin credentials with TypeScript in Firebase cloud functions

While working with Firebase cloud functions in JavaScript, I utilized the following code snippet to initialize admin: admin.initializeApp({ credential: admin.credential.cert(require('./key/firebase-adminsdk.json')), databaseURL: "https://app ...

Showcase data objects in JSX format

I have an Object stored in my state that looks like this: console.log(state) I've developed a component to display a card for each item within this object (which contains sub-objects). Despite trying multiple approaches, I keep encountering an error ...

When attempting to access Firebase Storage with Angular, you may encounter the error message: "TypeError: app.storage

Having trouble connecting my Angular app to FireBase. The component appears blank and the Chrome console is showing a 'TypeError: app.storage is not a function'. Any ideas on what I might be doing wrong? Thanks in advance. ng --version Angular C ...

Is there a minimal-impact generic tuple type available for storing [function,...params]?

How can I specify to the type checker that tuples must consist of a function and valid arguments? For example: let expressions:TYPE[] = [ [(a:number, b:string)=>{},1,"ok"], // ok [(a:number)=>{},true] // error [(a:number)=>{} ...

Ways to mimic an Angular subscription during a Jasmine test

I'm currently troubleshooting a unit test for my code (I'm not very experienced with Jasmine) after adding some subscriptions to a service. I'm encountering an issue where the subscriptions are coming up as undefined. I'm not entirely s ...

Angular: Activate async validator for form group only when all controls have values

Is there a way to trigger validation for FormGroup only after all the fields in the group have been filled out, instead of triggering it every time a field is filled? ...

Dynamically defined type literals in Typescript

Recently, I came across an intriguing problem. I am attempting to develop a Vue.js wizard component that takes in configuration objects. The type of demo I have looks like this: type WizardConfiguration = { steps: Array<{ name: string, fie ...

Checking the interceptor response in NestJs testing

I created a basic interceptor that removes a specific field from a response: import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } ...

Explore the capabilities of the Angular Ng2SearchPipeModule to enhance your search input

I used the ng2SearchPipeModule for an input search, but it's not working. I can't seem to find my error. In my HTML, all my books are within divs. Will typing a book title display all the divs? Of course, I have imported in app.module.ts Ng2Sear ...

Is it possible to store all data in the Redux store while using Angular?

As I develop an Angular form, I find myself working with numerous 'select' fields. I'd like to populate these select field options from the server. Would it be advisable to store this data in the ngrx store? Or would using services suffice t ...

Tips on resolving the issue of 'caught local exception thrown' while utilizing instanceof for identifying the type of internal errors

I've encountered a scenario where I'm loading a set of plugins in my code. Each plugin executes a series of functions within a try-catch block to check for failures and handle them accordingly. Some functions within the plugin can return specific ...

Select items displayed next to each other with varying number of columns in HTML

Users can select a medicine for each day of their plan, with the option to choose up to 7 days. I want to dynamically show a corresponding number of Select dropdowns based on the user's selection. body { width: 500px; margin: 0 auto; ...

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...