What is the best way to extract values from a specific table column and store them in an array using Angular?

I have a section of code containing a table in my component:

expect-next-month.component.html

        <table id="users">
            <tr>
                <th>Number of month</th>
                <th>Total checking electrical units</th>
                <th>Total assembly</th>
                <th>Total soldering</th>
                <th>Total packing</th>
                <th>Total working days in this month</th>
            </tr>
            <tr *ngFor="let sum of totalWorkPerMonth">
                <td>{{sum.number_of_month}}</td>
                <td>{{sum.total_checking_electrical_units}}</td>
                <td>{{sum.total_assembly}}</td>
                <td>{{sum.total_soldering}}</td>
                <td>{{sum.total_packing}}</td>
                <td>{{sum.total_working_days_in_this_month}}</td>
            </tr>
        </table>

The task at hand is to extract data from the total_packing column and store it in an array within the ts file for validation purposes. (This particular column consists of integer values).

I'm seeking guidance on accomplishing this. I attempted using ngModel, however without success. Any assistance would be greatly appreciated. Thank you!

Answer №1

1. One approach is to extract the data into a new array in your TypeScript file using the map function

var result = this.totalWorkPerMonth.map(x => x.total_packing)

// Perform verification for each item in your list:
result.foreach(packing => {
  // do something
}

2. Another method is to create a validation function for your attribute:

<td>{{validateField(sum.total_packing)}}</td>

In your .ts file:

 validateField(value: int) {
  // do something
  if (value < 0) return 0;
  else return value;
 }

3. The third solution, which I personally consider the most effective, involves conducting validation checks before rendering the results when receiving the data.

If you have a method getData() in your component and need to apply validation on a specific field:

getData() {
   service.getData().subscribe(data => {
      data.foreach(row => {
         // Conduct necessary validation as shown in example
         if (row.total_packing < 0) {
           row.total_packing = 0;
         }
      }
      this.totalWorkPerMonth = data;
   });
}

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

Adjust the specific data type to match its relevant category

Is there a method to alter literal types in TypeScript, for instance. type T1 = ""; type T2 = 1 I am interested in obtaining string for T1 and number for T2. Regarding collections, I am unsure, but I assume it would involve applying it to the generic typ ...

Angular 7 SPA encountering Media Type Not Supported 415 issue when communicating with .NET, despite successful request in Postman

My SPA is encountering a 415 Unsupported Media Type Error when it calls a specific endpoint in my .NET API that I recently implemented pagination for. Interestingly, the same call from Postman is successful without any errors. It's puzzling why the id ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

Error encountered in Angular 2 with RXJS Observable: Unable to call function catch() on this.http.get(...).map(...) due to TypeError

Everything was running smoothly with my Service until today, when I encountered the following error: TypeError: this.http.get(...).map(...).catch is not a function. Upon debugging the code, it crashes at the catch method. import { Test } from "./home.c ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...

Create a compilation of categories/interfaces based on a mapping

Imagine you have the following object: const ROUTES = { PAGE_NO_PARAMS: '/hello/page/two', PAGE_R: '/about/:id', PAGE_Z: '/page/page/:param/:id', PAGE_N: '/who/:x/:y/:z/page', } as const Can we create a set ...

Issue with Angular routing not functioning properly post form submission

Recently, I created a contact form using Angular for the frontend and NodeJs with Nodemailer for the backend. However, I encountered an issue where after submitting the form, instead of redirecting to the default page set in the app, the page remains on th ...

Direct your attention to utilizing directives when dealing with an empty ngselect

I have a form with a template driven design that includes a mandatory ng-select dropdown and a textbox. When I submit the form, certain conditions should be met: If the ng-select dropdown is empty, the focus should shift to the ng-select dropdown. If the ...

Creating a generic class in Typescript that can only accept two specific types is a powerful

When designing a generic class, I am faced with the requirement that a property type must be either a string or number to serve as an index. If attempting something like the code snippet below, the following error will be triggered: TS2536: Type 'T ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Angular, Node.js, NVM (Node Version Manager), and NPM (Node

I recently upgraded my Node version from v6.5.0 to v8.9.4 using nvm and noticed that npm also got updated to a newer version. Now, I have a few questions regarding this update: After switching to Node 8.9.4 with nvm, why does the command node -v still ...

Encountered an error while trying to access the 'touched' property of undefined within Angular6 reactive forms

When attempting to validate my page, I encountered an error stating 'Cannot read property 'touched' of undefined'. Can someone please assist me with this code? Also, feel free to correct any mistakes you may find. Here is the HTML code ...

Having trouble assigning a value of `undefined` to a TextField state in React hook

I am in need of setting the initial state for a TextField date to be undefined until the user makes a selection, and then allowing the user an easy way to reset the date back to undefined. In the code snippet below, the Reset button effectively resets par ...

Jest assertions encountering type errors due to Cypress

After using react-testing-library and @testing-library/jest-dom/extend-expect, I decided to install Cypress. However, I now face Typescript errors on all my jest matchers: Property 'toEqual' doesn't exist on type 'Assertion'. Did ...

There was an issue retrieving the metadata for the bootstrap package using the git+ssh protocol

While attempting to install angular devkit and other dependencies using npm install, I encountered the following error message: Could not retrieve metadata for bootstrap@git+ssh://example@example.com/gios/Web-Standards-Bootstrap.git#05a343dddce91dd157702 ...

Choosing the most suitable stylesheet in Angular 8 when multiple CSS files are present

In my project, I have several CSS stylesheets for angular components. I am curious if there is a method to designate a preferred stylesheet when multiple sheets loaded by a component contain the same styles but with different values. ...

Is there a surefire method to ensure that ChromeDriver in Protractor consistently uses the stable version?

Every time Chrome releases an update, I encounter a recurring issue. Allow me to paint the picture: All browsers are at version 83 of Chrome Chrome announces that version 84 is on its way, but it has not been released yet. A new ChromeDriver 84 is rolled ...

Sending properties to MUI Box component enhancer (Typescript)

I'm having trouble figuring out how to pass props to override the Box component. I specifically need to pass position="end" as InputAdornment requires it, but I can't seem to find the proper way in the documentation. Here's the complete co ...

Ways to showcase corresponding information for an item contained within an array?

I'm working with a function that is designed to retrieve specific descriptions for objects nested within an array. The purpose of the function (findSettings()) is to take in an array (systemSettings) and a key (tab12) as arguments, then use a switch s ...

Utilizing the FormsModule and ReactiveFormsModule within a Component module

I am facing an issue with integrating a reactive form into a generated component called boom-covers. I am utilizing the [formGroup] property as shown below: <form name="boomCovers" method="post" id="bomCovers" (ngSubmit)=&q ...