Looping through an object in Typescript using Angular 5

How can I gather data from an html page using ngModel and store them in a declared object? I want to then iterate through this object on the HTML page using ngFor.

I have already attempted this, but I encountered the following error:

The error message states: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

Answer №1

Utilize the Object.keys method to retrieve keys (which returns an array of strings) and loop through it. Check out this Demo

Assume you have an object named obj:

  obj = {
    apple: "A fruit",
    ball: "A thing to play with"
  }

  get keys(): string[] {
    return Object.keys(this.obj);
  }

In your template:

To display keys only:

 <div *ngFor="let key of keys">{{ key }}</div>

output:

apple
ball

To display values only:

<div *ngFor="let key of keys">{{ obj[key] }}</div>

output:

A fruit
A thing to play with

To display both Keys and values:

<div *ngFor="let key of keys">{{ key }} : {{ obj[key] }}</div>

output:

apple : A fruit
ball : A thing to play with

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

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

Error: The method "next" cannot be used with BehaviorSubject

My goal is to share data between sibling components by utilizing a shared service. The first component loads and retrieves a list of Servers from the API, populating a select box with all the servers. I now need to notify the other component when the user ...

How to separate an array of objects into individual arrays using Typescript reduce based on a specific property

I have the following array: statisticsOfScrapDeliveriesItems:[ { supplierId: "0001055404", deliveredFrom: "METALLCO AS", centerId: "C45", materialId: "TS0180", }, { sup ...

How to prevent selection of certain days in an Angular date input

I need help with my Angular component that includes an input date field. I am trying to figure out how to disable all past dates and also a specific range of future dates, such as those between 2023-10-15 and 2023-10-23. Is there a way to achieve this func ...

Determining the argument data type when calling the function

const func = <T>( obj: T, attr: keyof T, arr: T[typeof attr][], ) => { } const obj = {foo: 1, bar: true}; func(obj, 'foo', [1]); func(obj, 'bar', [1]); // shouln't be ok func(obj, 'foo', [true]); // shoul ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

Using Angular promises with a specific condition

In my code, I am trying to avoid hitting the endpoint (getUserInfo) if I already have a value stored in a variable. However, I believe there is redundant code in my current implementation and I am seeking suggestions for a more efficient approach. Below ...

The error thrown is: "TypeError: device.devices.map is not a valid function

I encountered an error after adding products to the page and I'm having trouble identifying the cause. const {device} = useContext(Context) 91 | </div> > 92 | <div className="inner-display-collection"> | ^ ...

Encountering an error due to an invalid type union when creating a new instance of a

My TypeScript code includes a Logger class that has an optional options parameter in its constructor. The options parameter includes a class generic C which represents custom levels. These custom levels are used within the class for methods like log(level: ...

Generate a new array, specifying its type, and populate it by utilizing Angular

My current situation involves a variable that is an array with the type Club. Within this array, a function is responsible for populating it. clubs: [Club]; This function is as follows: this.authService.getAllClubs().subscribe( clubs => { ...

Active Class in Angular Dynamic Carousel

I recently set up a dynamic carousel that pulls images directly from a node backend. While everything seems to be in working order, I've run into an issue where all the images are being displayed at once instead of sliding through one at a time. This ...

The test.ts file does not contain any type definitions

While I am able to successfully utilize my types in .ts files, I am facing difficulties in understanding why it's failing in .test.ts files, even though both files are located in the same folder. Check out the code in the .ts file below: https://i.s ...

Creating a dynamic method to set data for a stacked bar chart in chart.js

In the following code snippet, you can see how my stacked bar chart is rendered using Angular: <canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]=" ...

Organizing Ionic Cards in Alphabetical Order

I'm working on a personal project where I want to implement an alphabetical filter. Each time I create an Ionic card, I intend for it to be filtered by the first name, such as Andre, Amber, Beckc, etc... Here's what I have so far: https://gyazo.c ...

How can I only accept one of two specific function signatures in Typescript and reject any others?

Looking for an answer from the community on Typescript, require either of two function signatures In my code, I am handling a callback where I need to either pass an error or leave the first argument as undefined and pass data as the second argument. To ...

Transform a row in an ng Smart table to a routerlink using Angular 2

I've been exploring ng2 Smart Table and I'm looking to convert a row (or even cell data) into a clickable link using routerlink. The current method I'm employing to retrieve some of my row's data is as follows: onUserRowSelect(event) ...

Issue with Displaying Local Server Image in Angular 2 HTML

I am facing an issue with my Angular 2 Application. It retrieves items from a local database where the server stores the image of the item and the database stores the path to that image stored on the server. While I can retrieve all the items without any p ...

When performing the operation number.tofixed in Typescript, it will always return a string value instead of a double datatype as expected from parseFloat

let value = 100 value.toFixed(2) -> "100.00" parseFloat(value.toFixed(2)) -> 100 I am encountering an unexpected result with the double type when input is 100.36, but not with 100.00. Framework: loopback4 ...

Leverage bespoke webpack configuration in an Angular project

I needed to implement webpack in my Angular application, so I included the following code. package.json file "scripts": { "start_ar": "ng build --watch --configuration=dev_ar", }, "devDependencies": { "@angular-builders/custom-webpack": "^7.1.4", "file ...