Loop through an array of objects using *ngFor in Angular

My version is 13.0.4

I'm attempting to use ngFor in component.html but it's not displaying anything and causing page bugs. html:

<select>
    <option *ngFor="let region of regiones" value="{{ region.numero }}"> {{ region.nombre }} </option>
</select>

My Interface:

export interface Region {
    nombre: String,
    numero: number
}

I retrieve the regions from a Service (regiones.service.ts)

import { Injectable } from '@angular/core';
import { Region } from '../interfaces/regiones.interface';
import { HttpClient } from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class RegionesService {

  constructor(private _http: HttpClient) { }

  private _regiones: Region[] = [
      { nombre: 'Región Metropolitana de Santiago', numero: 0 },
      { nombre: 'Región de Arica y Parinacota', numero: 15 },
      { nombre: 'Región de Tarapacá', numero: 1 },
      { nombre: 'Región de Antofagasta', numero: 2 },
      { nombre: 'Región de Atacama', numero: 3 },
      { nombre: 'Región de Coquimbo', numero: 4 },
      { nombre: 'Región de Valparaíso', numero: 5 },
      { nombre: 'Región del Libertador General Bernardo O’Higgins.', numero: 6 },
      { nombre: 'Región del Maule', numero: 7 },
      { nombre: 'Región del Ñuble', numero: 16 },
      { nombre: 'Región del Biobío', numero: 8 },
      { nombre: 'Región de La Araucanía', numero: 9 },
      { nombre: 'Región de Los Ríos', numero: 14 },
      { nombre: 'Región de Los Lagos', numero: 10 },
      { nombre: 'Región de Aysén del General Carlos Ibáñez del Campo', numero: 11 },
      { nombre: 'Región de Magallanes y la Antártica Chilena', numero: 12 },
  ]
  

  getRegiones() { 
    return { ...this._regiones };
  }

}

Then I fetch them in a component: (inicio.component.ts)

export class InicioComponent implements OnInit {

  constructor(private regionesService: RegionesService) { }
  regiones: Region[] = this.regionesService.getRegiones()

  ngOnInit(): void {
    console.log(this.regiones);    
  }

}

This is the output in the console:

console log image

Result:

result

Error:

core.mjs:6469 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.ngDoCheck (common.mjs:3156:27)
    at callHook (core.mjs:2536:1)
    at callHooks (core.mjs:2495:1)
    at executeInitAndCheckHooks (core.mjs:2446:1)
    at refreshView (core.mjs:9484:1)
    at refreshComponent (core.mjs:10640:1)
    at refreshChildComponents (core.mjs:9265:1)
    at refreshView (core.mjs:9519:1)
    at refreshEmbeddedViews (core.mjs:10594:1)
    at refreshView (core.mjs:9493:1)

Answer №1

The issue lies in the getRegiones() method:

return { ...this._regiones };

Instead of returning an object, you should return an array to avoid Angular's error regarding looping through it.

To fix this, you can use

*ngFor="let region of Object.values(regiones)"
to convert it back to an array or adjust the output of the getRegiones() method.

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 it possible to generate one or more observables for a particular topic within a service?

After researching various sources and websites, it is apparent that there are two distinct approaches to creating a service with a subject/observable for data sharing: One approach involves initializing an observable of the subject and returning it (refer ...

Exploring the hidden gems of npm package.json: the keys

There are some keys in the package.json file of Angular 2/4's source code that remain undocumented: { "name": "@angular/platform-browser/animations", "typings": "../animations.d.ts", "main": "../bundles/platform-browser-animations.umd.js", "m ...

Having difficulty incorporating an input value into an Angular function

For a school project, I am creating a login form using Angular. Below is the HTML code: <input type="text" ng-model="username" name="username" /> <input type="text" ng-model="password" name="password" /> <button (click)="submit(username, pa ...

Converting HTML to PDF using Angular

Looking for a way to download my Angular (HTML) project that utilizes the primeng UI library as a PDF with searchable content. Most tools I've come across only convert the DOM into an image, which is not what I need. Below is a snippet of my code tha ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Dynamic getter/setter in Typescript allows for the creation of functions

I'm facing a challenge in making Typescript automatically infer types for dynamically created getter and setter functions. In my code, I have a class called MyClass which contains a map of containers: type Container = { get: () => Content s ...

Node.js with TypeScript: The block-scoped variable 'events' cannot be redeclared

I am currently in the process of migrating a Node + ES6 project to TypeScript. My goal is to stick to ES6 (since I am using Node 7.x) and incorporate the use of Map. Upon running tsc -p, the following errors are displayed: src/actions.ts(3,9): error TS2 ...

I'm encountering issues with undefined parameters in my component while using generateStaticParams in Next.js 13. What is the correct way to pass them

Hey there, I'm currently utilizing the App router from nextjs 13 along with typescript. My aim is to create dynamic pages and generate their paths using generateStaticParams(). While the generateStaticParams() function appears to be functioning corre ...

Error message: "ExpressionChangedAfterItHasBeenCheckedError - encountered while using ngIf directive to hide/show a progress

My HTTP interceptor is set up to display a loading bar whenever an HTTP request is made: intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const dataStorageService = this.injector.get(DataStorageService); ...

Issue with mailgun causing email to not send and returning undefined data

Trying to set up a basic email confirmation process for signups using Angular 4, Node.js, mailgun-js and mailgun, but encountering issues with the mailgun send method. mailgun.messages().send(data, function(error, body) { console.log(body); }) ...

Having trouble accessing data from .env file in Typescript

I am struggling to configure my typescript setup to properly read data from the .env file. For some reason, the variable ${string} is not being recognized in this context. const MONGO_URL='mongodb+srv://${MONGO_USERNAME}:${MONGO_PASSWORD}@cluster0.r25 ...

What is the best way to ensure that at least one option is selected when using Angular Material toggle with multiple choices?

Is there a way to allow users to select multiple options but prevent them from deselecting a button if it is the only choice available? Code Snippets: <mat-button-toggle-group (change)="changeOpt($event)" multiple name="fontStyle" aria-label="Font Sty ...

What is the best approach for defining variables in typescript?

Let's talk about creating a variable for a car: export class ICar { wheels: number; color: string; type: string; } So, which way is better to create the variable? Option one: const car = { wheels: 4, color: 'red', type: &apos ...

I encountered difficulties accessing the native Camera API when working with the most recent version of Ionic

Every time I try to run $ ionic cordova plugin add @ionic-enterprise/camera I encounter the following error message [OK] Integration cordova added! ✔ Creating ./www directory for you - done! > cordova plugin add @ionic-enterprise/camera You have ...

Creating a TypeScript record with the help of the keyof operator and the typeof keyword

I have an object set up with my enum-like times of day and I am attempting to create the correct type for a record based on these entries. export const TIMEOFDAY = { FirstLight: 'First Light', Morning: 'Morning', Antemeridie ...

Preventing image flickering in SvelteKit: A guide

Upon the initial loading of a website, you may notice that the images tend to flicker or flash when transitioning between them. However, once these images are stored in the browser's cache, subsequent visits to the site will display the images seamles ...

Display various react components based on the value of the property

I am in the process of creating an input component in ReactJs with typescript. The input can vary in types such as text, date, select, or textarea. Depending on the type provided, the displayed control will differ. For example, if set to text, <input t ...

Struggling with resolving Angular dependencies

Every time I try to run npm install or any other npm command, a string of dependency errors pops up, leaving me puzzled on how to resolve them. Here are the steps I've taken so far:--> Forced update of angular CLI. Reinstalled Node. I eve ...

Unable to integrate Tailwind CSS into my React, TypeScript, Sass, and Vite stack

Currently, I am working on a React + TypeScript application. My styles folder is located inside the assets folder within src: src/assets/styles/global.scss This app is built using Vite. I have attempted various configurations and fixes for an issue I en ...

If a generic string argument is not specified as a string literal, it will not be narrowed unless it is the first argument

When the following code is executed, it works as intended and we can see that the arg variable is a string literal: const foo = <T extends string = string>(arg: T) => {}; foo('my string'); // const foo: <"my string">(arg ...