Searching for an element in an array that meets specific criteria using Angular 7 within HTML code can lead to a Parser Error

My Mockup-data has a structure similar to this:

           "data": {
                "name": "rowValue1",
                "hours": [
                    {
                        "year": 2018,
                        "month": "October",
                        "number1": 100,
                        "number2": 80,
                        "diff": 20
                    },
                    {
                        "year": 2018,
                        "month": "November",
                        "number1": 100,
                        "number2": 80,
                        "diff": 20
                    },
                    {
                        "year": 2018,
                        "month": "December",
                        "number1": 100,
                        "number2": 80,
                        "diff": 20
                    },
                    {
                        "year": 2019,
                        "month": "January",
                        "number1": 100,
                        "number2": 80,
                        "diff": 20
                    }
                ]
            }//...

When iterating through the column-objects to build a header, I need to extract values from my data based on certain criteria. Each column must have the fields: month, year, and a field which could be number1, number2, or diff. In order to extract the correct value from my hours-array, I tried using the Array.find() method within my HTML code.

https://i.sstatic.net/3Zww4.png

The goal is to identify the right entry in the array based on the provided parameters. For instance, instead of having the value for number1, I want to fetch the exact element from the hours array, such as 100 in the example above. The attempt to use Array.find() resulted in an error when running ng serve:

Uncaught Error: Template parse errors: Parser Error: Bindings cannot contain assignments at column 27 in [{{rowdata.hours.find(entry => entry.year == col.year && entry.month == col.month)[col.field]}}] in

This indicates that there might be a problem with the assignment inside the arrow function entry => (...). Is there an alternative approach to finding the correct entry in the array?

Answer №1

To simplify your code, you can create a method within the component to handle the logic and return the value of the specified column.

Within your .ts file:

getColumnValue(col: any) {
   return this.rowData.hours.find(entry => entry.year === col.year && entry.month === col.month)[col.field];
}

Then, in your template, call the above method like this:

<tr *ngIf="rowData.hours"><td *ngFor="let col of columns" style="height: 50px">{{this.getColumnValue(col)}}</td></tr>

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

Using route variables in Angular 11 right after defining them: A quick guide

How can I utilize route variables in order to set the breadcrumb title dynamically? For example: { path:'sample/:title', data:{ breadcrumb:[ {title:'sample',link:'sample'}, {title: how do I use the :title variable her ...

When converting to JSON, objects may sometimes lose their properties

Here is a sample of my class structure: export class Patient { constructor(public id: number, public name: string, public location: string, public bedId: number, public severity: string, public trajectory: number, public vitalSigns: [GraphData[]], public ...

Is there a way to adjust the font size for the label in mat-step?

Is there a way to update the design using only inline styles and CSS? Below is the code snippet I am working with: <div class="statusbar"> <mat-horizontal-stepper linear > <mat-step label="One" [complet ...

When employing `queryParams` in Angular routing, the URL will automatically replace `%` with `%25`

When trying to use queryParams for navigation in Angular routing, I encountered an issue. <a routerLink='/master' [queryParams]="{query:'%US',mode:'text'}"><li (click)="search()">Search</li></a> The d ...

To ensure the specificity selector for material UI in React, it is essential to include an empty CSS definition

The styling for the unselected toggle button is working smoothly. However, when you don't define an empty class selector, the style of the selected toggle button does not show: ./App.js import * as React from "react"; { render ...

When utilizing three.js/react/vite in a project, the build process may encounter issues when built with vite and the TypeScript compiler. However, the project functions properly when running npm run dev

I recently embarked on a project utilizing three.js, react, and vite. As I delved deeper into the development process, I found myself hesitant to fully commit to integrating React into my project. Consequently, most of the React code within my project serv ...

Creating TypeScript types using GraphQL code generation: Generating types without any other code

Utilizing the typescript plugin for graphql code generator As documented This TypeScript plugin is fundamental and capable of creating typings from GraphQLSchema, which can be leveraged by other typescript plugins. It creates types for all aspects of you ...

I rely on Nebular for my Angular application, however, I am looking to make some manual CSS changes that I am having difficulty implementing

While using Nebular for my Angular app, I have run into issues with changing some CSS manually. Specifically, when using nb-select or nb-toggle, I am unable to customize the CSS as desired. Do you have any suggestions to help me with this problem? enter i ...

Highcharts 7 - Positioning an Annotation in the Center

I would like to display an annotation above specific data points on my Highchart. Currently, the annotation appears at the location of the data, but it is not centered directly over the point. I want the annotation to be perfectly centered on the data poin ...

Display the Angular Material sidebar within the parent component's closing tag

I am using an angular material sidenav, but every time I open it, the sidenav is always positioned at the left side of the window https://i.sstatic.net/80VQ0.png However, I want the sidenav to always open at the end of the component with a blue backgroun ...

Change the @select variable to an object, a basic variable, or delete the AnonymousSubject

I'm utilizing Redux architecture within Angular. In my component, I am accessing the state's value using the @select (select pattern). However, when I try to log the @select variable to the console, I see the output as AnonymousSubject. ...

How can I enable email and password login in @auth0/auth0-angular?

Auth0 SDK for Angular Single Page Applications - the documentation outlines two methods for logging in: loginWithPopup loginWithRedirect Is there a possibility to add another option for logging in with just an email and password? ...

Tips for populating the header of an angular-material card

I am working with an angular-material classic card that has the following template: <mat-card class="example-card"> <mat-card-header> <mat-card-title>Shiba Inu</mat-card-title> </mat-card-header> <mat-card-conten ...

How come the hasOwnProperty function does not remove objects of type {}?

I am working with a complex type called ReactNode from the version @types/react 16.9.17 and TypeScript v3.7.4. import React, { ReactNode } from 'react'; My goal is to reduce this type to a new type that includes the property children. To achie ...

What is the best approach for associating interfaces with nested objects to ensure proper configuration validation?

Exploring the use of typescript for implementing type checking on a configuration file similar to the one below: const _config = { local: { host: 'localhost', port: 1234 }, dev: { host: 'https://dev.myapp ...

Combining Angular and Material Design: matdrawer and mattoolbar creating an overlapping effect

I'm currently facing a challenge in trying to construct a drawer that includes a mattoolbar, intended to overlap the primary toolbar of my application. Despite my efforts, I have been unable to rearrange the drawer higher up in the component hierarch ...

Showing a 2D array in HTML using ngFor loop

I need to display a list of arrays in an HTML p-table. Here is the array list: [Array(2), Array(2), Array(2), Array(2), Array(1)] 0: (2) ["abc", "def"] 1: (2) ["ghi", "jkl"] 2: (2) ["mno", "pqr"] ...

Exploring nested JSON structures with RxJS

Currently, I have a JSON file deployed on the server structured like this: { "data": [ { "id": 1, "name": "Angular Connect", "date": "2036-09-25T23:00:00.000Z", "time": "10:00 am", "price": 599.99, "imageUrl": "/a ...

What is the most effective method for structuring JSON data that is utilized by a single-page application (SPA)?

A colleague and I are collaborating on a single page application (built in React, but the framework used isn't crucial; the same query applies to Angular as well). We have a database with 2 interconnected tables: Feature Car Both tables are linked ...

Using Angular 2's @ViewChild to access elements within a loop

I'm currently working on building a table with a specific structure. Odd rows contain data, while even rows are meant to expand when clicked. I am encountering difficulties in dynamically loading data into the expandable row upon user interaction. I& ...