Breaking up assignments in a loop with Angular's *ngFor

Having issues while attempting to iterate through a JavaScript dictionary within my HTML markup using *ngFor with Object.entries, and encountering an error message:

Error: Unexpected token [, expected identifier, keyword, or string at column 5 in [let [key, item] of Object.entries(items)]

Here is the template:

<button *ngFor="let [key, item] of Object.entries(items)" 
        (click)="itemClicked.emit([key, item.value])">
  {{ item.displayName }}
</button>

And here is the TypeScript code:

export interface DropDownItem {
  displayName: string,
  value: any,
  checked: boolean
}

@Component({ /* ... */ })
export class MyComponent {
  @Input() items: { [key: string]: DropdownItem };

  @Output() itemClicked = new EventEmitter<[string, any]>();

  Object = Object;

  constructor() { }
}

Answer №1

After some tweaking, I ended up with the following code snippet in my markup; it remains unchanged.

<button *ngFor="let key of Object.keys(items)"
        (click)="itemClicked.emit([key, items[key].value])">
  {{ items[key].displayName }}
</button>

I still have a desire to destructure the Object.entries() within my markup, but unfortunately it seems that destructuring is not currently supported for *ngFor.

While browsing, I came across this feature request from a couple of years ago requesting destructuring in *ngFor syntax. The response indicated that they had decided against implementing this feature, but I'm holding out hope that they may reconsider in the future.

Answer №2

Another approach would be to utilize Angular's KeyValuePipe:

<button *ngFor="let entry of items | keyvalue" 
        (click)="itemClicked.emit([entry.key, entry.value.value])">
  {{ entry.value.displayName }}
</button>

This version is slightly similar to your initial one, but the entry hasn't been broken down into destructured parts.

Answer №3

In theory, you can still access the key and value pair without destructuring, even though it may not be considered the best practice in terms of style:

<button *ngFor="let entry of Object.entries(items)" 
        (click)="itemClicked.emit([entry[0], entry[1].value])">
  {{ item.displayName }}
</button>

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 absence of Index.ts in the TypeScript compilation cannot be resolved by simply including it

Upon integrating @fireflysemantics/slice into my Angular project, I encountered the following error: ERROR in ./node_modules/@fireflysemantics/slice/index.ts Module build failed (from ./node_modules/@ngtools/webpack/src/index.js): Error: /home/ole/Temp/fs ...

What is the method for showcasing a specific value using a filter?

In my app, I have the following data: birthdayGreetings:Array<any> = [ { name: 'John', date: new Date(1994, 3, 19), greeting: 'Happy Birthday, John! Good luck!', displayName: false } ]; I ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

Is it possible to utilize an await in an rxjs observable?

Implementing an interceptor for my HTTP requests requires the use of the access token from the user instance. Within my app component, I initialize the user: app.component.ts private async restoreUser(): Promise<UserModel | any> { // ... some vi ...

An illustration of an Angular 2 animation reaching its end and triggering a callback function

I'm currently working on developing a function in Angular 2 that should be activated at the conclusion of an animation. I am utilizing the most recent angular cli and have been exploring the Angular Animations documentation to grasp how to implement t ...

The edited input is not being shown on the console when using the PUT method

I retrieved the data for the input fields (title and body) from this specific source (https://jsonplaceholder.typicode.com/posts). My goal now is to modify the text in either the title or body, so that when I use console.log(), it will show the updated tit ...

Guide to setting up front-end code coverage in SonarQube for an Angular application

Here is my dashboard in Bamboo regarding Sonarqube: https://i.sstatic.net/FU7c9.jpg This is how the project build result page appears: https://i.sstatic.net/DRltU.jpg I am looking to integrate test coverage in Bamboo to view unit test reports, as we alre ...

Select and activate a single input from multiple options in Angular

I have multiple input fields with corresponding buttons that enable the input when clicked. I would like the behavior of the buttons to work in such a way that when one button is clicked, only that specific input field is enabled while the others are disab ...

Angular2 RC5 and the issue with routing: No routes found to match

Currently, I am experimenting with implementing rc5 along with routes in my application. This is the functionality I am aiming to achieve: Navigate to the login page After successful login, redirect to the dashboard route which has a navigation bar at t ...

Component coding in Angular 2 allows for seamless integration and customization of Material

I am looking to initiate the start.toggle() function (associated with Angular 2 material md-sidenav-layout component) when the test() method is triggered. How can I execute md-sidenav-layout's start.toggle() in the app.component.ts file? app.componen ...

Customize the filename and Task Bar name for your Electron app when using electron-packager

My application uses electron packager to build the app on Mac. Here is my package.json configuration: { "name": "desktop_v2" "productName": "desktop v2", "version": "1.0.0", "license": "MIT", "scripts": { "build": "node --max_o ...

How can a fixed type value be assigned to a portion of a type that is constrained by generics?

Experience a new aspect of Ids with my basic interface: interface Identifiable { id?: number; } Behold, a universal function that transforms record objects into entities with ids: function transformRowToObject<T extends Identifiable>(row: { id: ...

What causes error TS2345 to appear when defining directives?

Attempting to transition an existing angular application to typescript (version 1.5.3): Shown below is the code snippet: 'use strict'; angular.module('x') .directive('tabsPane', TabsPane) function TabsPane(ite ...

Angular 2 client for Spring Boot Birt Report produces faulty PDF documents

I am currently setting up a BIRT report within a Spring Boot application that is being accessed by an Angular 2 client. Below is the code snippet where the report is executed: @PostConstruct public void startUp() { if(inputDir == null) throw n ...

Retrieve data from a table within an Angular component

Struggling with the ng2-smart-table library, I am facing challenges in passing values entered in the edit line to a custom component: Refer to the code snippet below for passing Maximum and Minimum Temperature values to the SmartTableEditorFunctionsCompon ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

The Vue application encountered an issue while trying to mount the component due to the absence of a defined template or render function. The error was triggered

Here is the code snippet for my component: <template> <uploader class="uploader-example"> <uploader-unsupport></uploader-unsupport> <uploader-drop> <p>Drop ...

Showing Information without NgFor Directives

I have successfully displayed data without using a ngFor loop. However, it is currently showing all the quote information from multiple customers. The CSS is arranged in such a way that the discount div is positioned next to the customerinfo div. Below is ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Is `TypeDefinition for React v15.0` compatible with React v0.14.7?

Within the project I am currently working on, we have incorporated React v0.14.7. After using npm, I executed the following command: npm install --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccbea9adafb88cfce2fdf8e2fb ...