How to loop through object keys using *ngFor in the latest version of Angular

When attempting to iterate through the "others" array using *ngFor in Angular, I successfully accessed the "id" and "year" values. However, when trying to loop through the "others" array, I encountered the issue of receiving [object object] as the output.

{
        "id": 11,
        "year": [
            2019,
            2020
        ],
        "others": {
            "name": "John",
            "age": "19",
            "work": "yes"
        }
    }

Answer №1

Aha, I understand now! Utilizing the safe navigation operator ?, we can access the property like this: data.others?.name

Answer №2

String interpolation cannot be used to directly call an object, however, you can access individual properties of the object.

<h1>{{others}}</h1> // output [object object]

// Instead, do this

<h1>{{others.name}}</h1>

An object cannot be iterated through like a collection.

Answer №3

In order to utilize *ngFor with objects, you must include the "key value" pipe.

<div *ngFor="let item of object | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

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

How can I convert an object to JSON using JSON.stringify and ensure its type is recognized as JSON?

When I attempt the following code snippet: import { MyType } from 'somewhere'; class MyClass { myObj: MyType = new MyType(); updateObject(newVal: string): void { myObj.thing = newVal; this.saveStuff(JSON.stringify(myObj ...

Using TypeScript's interfaces to push items

Can anyone provide some guidance on working with interfaces in typescript? I currently have the following 3 interfaces: export interface HomeMenu { [name: string]: MenuItem; } export interface MenuItem { title: string; route: string; hom ...

How can we achieve a programmatic single selection in PrimeNG Tree v16 with checkbox selection option?

Currently, I am working on implementing the PrimeNG Tree component in Angular with selectionMode set to "checkbox". My goal is to achieve a programmatic single selection where selecting a child node automatically unselects all other child and parent nodes ...

Setting an Observable reference to null within a map operator does not have any impact

I am currently working on developing a generic DataService that includes hateoas implementation. Within this setup, there is a REST API endpoint called /root which provides all the required hateoas links. For instance, { _links : { login : { ...

Issue with a child element that is malfunctioning because of the parent element

There seems to be an issue with the child tag link not working because of the parent tag link. Is there a solution for this problem? Please provide suggestions. Here is the code snippet: <div class="d-flex flex-wrap mx-auto mb-4"> < ...

data being released from variables in angular ionic

I am truly perplexed as to why the variables aren't holding their values. I've declared a variable user and initialized it with data from the userData() function. However, it appears as undefined when I log it within the constructor as well as ...

The installation process of Meteor npm sometimes selects an incorrect version from the package.json file

Initially, my meteor project's package.json contained all Angular libraries at version @2.0.0-rc.4. However, I decided to update them to version 2.0.1. The updated package.json now looks like this: { "name": "angular2-meteor-base", "private": tru ...

Issue with Angular modal popup not repositioning upon clicking elsewhere on the page

I have encountered an issue with modal popups on my website. Specifically, I have approximately 100 table elements and when I try to edit the element #100, the modal popup appears at the bottom of the page. However, if I scroll back up and click on eleme ...

MatFormFieldControl with custom styling is failing to display the initial value in the view

Take a look at the stackblitz example here: https://stackblitz.com/edit/angular-material-components-demo-5k6gey?file=src/app/app.component.html An issue arises when there is an initial value present in the view, as it is not displayed properly. Additional ...

Form nesting with control value accessor usage

In my current setup, I have one container component with two child components: Trip and Contact. To nest the child components within the parent, I have implemented ControlValueAccessor. I created an AbstractValueAccessor class that implements ControlValueA ...

What is the best way to incorporate auto-completion into a browser-based editor using Monaco?

Recently, I embarked on a project to develop a browser-based editor using monaco and antlr for a unique programming language. Following an excellent guide, I found at , gave me a great start. While Monaco provides basic suggestions with ctrl + space, I am ...

Ways to sort mat-select in alphabetical order with conditional names in options

I am looking to alphabetically order a mat-select element in my Angular project. <mat-select [(ngModel)]="item" name="item" (selectionChange)="changeIdentificationOptions($event)"> <mat-option *ngFor="let item of items" [value]="item"> ...

DomSanitizer in Angular is not able to bind to an Angular component

Trying to dynamically insert HTML content into a DIV has been successful when done statically. The following code is functioning properly: <popover-content #pop1 title="Cool Popover" placement="right" ...

Optimal asset management strategies for Angular applications

What is the process for loading assets in an Angular app? Will the app wait for all assets to load before bootstrapping, or will they be lazy loaded if not needed on the initial page? I have a large number of PDFs stored in the assets folder that I load a ...

Is it necessary to retrieve the data that was posted from the back-end? Implementation using Angular and Node.js

I need some advice on how to handle worker data in my Angular, NodeJS, and MySQL app. In the FORM, users can add workers whose information is then sent to the backend for processing. The user can preview the posted information and delete workers if needed. ...

Update ngx-datatable when the user clicks on a different directive

My issue involves a Side Navigation with a docking feature and a data table in the Main View. When I undock the side navigation, the data table does not recalculate automatically, leaving empty space where the Side Navigation was. This requires me to manua ...

The reason behind the ghost problem - classRef isn't recognized as a constructor

Recently, I encountered an issue where the app was not loading in the browser while running an Angular NX project locally with the command "start-dev": "nx run-many --target=serve --all". The screen would get stuck on our loading animat ...

Who is responsible for ensuring that the data has been successfully stored in the state?

As I work on utilizing SSR with TransferState, a question arises about the assurance of data storage in the transferState. This concern stems from the asynchronous nature of http.get, which may result in content delivery to the client before the desired ...

The route configuration is invalid: it is not possible to use 'redirectTo' and 'canActivate' together

I am looking to implement Laravel Angular JWT authentication, and I am encountering an issue with applying a guard. The error message states: Invalid configuration of route '': redirectTo and canActivate cannot be used together. Redirects happen ...

What is the most effective way to dynamically display or conceal sections of a string in Angular?

In the process of creating a template, I am faced with the challenge of constructing a URL string using various fields from a JSON response. The issue arises when some sections of the string may be empty, such as not having a value for 'path2', f ...