In Typescript, is there a way to retrieve the name of an object when working with object types?

I am working on creating a for() loop to check the first field in my template with the status INVALID and I need to retrieve the name of this object.

This is what I have tried so far:

for(var mandatoryField in form.controls){

  if(form.controls[mandatoryField].status == "INVALID"){
    var displayedMandatoryField = form.controls[mandatoryField];
    console.log(displayedMandatoryField)
    return ;
  }

}

It seems like my logic is correct, but I am not able to get the name of my object in this line:

var displayedMandatoryField = form.controls[mandatoryField];

I want to traverse the DOM tree to find the object with the status INVALID, but I only need its name. For example: height, length, etc...

https://i.sstatic.net/abz2V.png

Any suggestions on how can I achieve this?

Answer №1

If you want to iterate over iterable objects, consider using the for...of statement instead of for...in loop in your code snippet:

for(var campoObrigatorio of formulario.controls){

  if(campoObrigatorio.status == "INVALID"){
    console.log(campoObrigatorio);
    return 
  }

}

The for...of statement is used to create a loop that iterates over iterable objects such as built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It triggers a custom iteration hook with statements executed for each distinct property value of the object.

Find out more about for..of Here.

Answer №2

When looping through your form controls, you already have access to the property name by default which is represented by var campoObrigatorio. Therefore, the following code snippet should meet your requirements:

for(var campoObrigatorio in formulario.controls){
  if (formulario.get(campoObrigatorio).status === "INVALID") { // Using get for clarity
    console.log(campoObrigatorio) // This will display the control's name
    return;
  }
}

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 input argument must be of type 'PollModel', as the property 'pollId' is required and missing in the provided 'any[]' type

Hey there! An issue popped up when I tried to pass an empty array as a model in my Angular project. The error message reads: "Argument of type 'any[]' is not assignable to parameter of type 'PollModel'. Property 'pollId' is ...

Tests in Angular2 are executed before the variables in compileComponents are initialized

I'm encountering an issue with an Angular2 text component where I receive the following error message when trying to run the testrunner: Component: Product Component Should ensure component subscribes to service EventEmitter on instantiation Failed: ...

Challenges encountered when trying to showcase API data in Angular 6

In my application, I am making a call to the iTunes API and when I check the response, it is showing as [object object]. I believe this might have to do with the way the API's array structure is set up. I have a service injected into a component setup ...

Header and footer that stick in place while content scrolls automatically

To create a layout where the header and footer remain sticky while the content has a minimum height and shows a scrollbar when the viewport is too small, I found success with this codepen: http://codepen.io/DlafCreative/pen/wzdOEN inspired by another sourc ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Encountering a Prettier error with React Native 0.71 and Typescript

https://i.stack.imgur.com/h9v5X.pngThe app runs smoothly, but these red warnings are really bothering me. How can I resolve this issue?https://i.stack.imgur.com/NebzJ.png ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

AngularJS Dilemma: Virtual Machine Data Set but No Rendering in Sight

Below is the AngularJS controller code written in Typescript: /// <reference path='../../definitions.d.ts' /> module baseApp.viewControls.products { export interface IProductsScope extends IAppScope { vm: { product ...

Troubleshooting Angular 7 Build Failure: Missing Typescript .d.ts Declaration Files for Ahead-of-Time Compilation

I have encountered difficulties in building my Angular 7 application after upgrading from v6. When I use ng build, everything runs smoothly. However, when I try either ng serve --aot, ng build --aot, or ng build --prod (which also includes aot), an error ...

What is the general consensus on combining SWR with Redux - is it considered a best practice?

I am currently incorporating both SWR and Redux into my code. Here is how I'm using them together: const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX const response = useFetch("/vehicles/states") // SWR con ...

What is the best way to integrate Greensock CustomEase with TypeScript?

Currently, I am developing a game using Typescript with PixiJS and GreenSock (or is it GSAP?) for handling all the tweening. I recently encountered a situation where I needed to implement some custom easing using cubic-bezier curves. GreenSock provides a C ...

Webpack encountering module resolution issue with Stripe.js

After inserting the script tag for Stripe.js into my index.html: <script type="text/javascript" src="https://js.stripe.com/v2/"></script> Webpack is throwing an error message: Module not found: Error: Can't resolve 'stripe' ...

ESLint encountered an issue while attempting to load the configuration "plugin:@angular-eslint/ng-cli-compat" for extension

After attempting to upgrade my Angular project from version 15 to 16, I am now facing a series of perplexing errors. IntelliJ is displaying the following error at the top: https://i.stack.imgur.com/nCS2M.png Furthermore, when trying to run ng serve, it f ...

Ways to output a React component using TypeScript

Looking for guidance on how to print a React component using TypeScript when a button is clicked. I'm new to both React and TypeScript and would like to know how to achieve this functionality in my project. ...

Steps for dynamically assigning component references in Angular 4

When working with components, is there a way to dynamically assign component references like this: <app-list-audit #LAref{{identifier}}></app-list-audit> as opposed to <app-list-audit #LAref2></app-list-audit> ...

Fetching DataItem from a Kendo Grid using a custom button in an Angular application

I have been working on transferring the dataItem from a Kendo grid to an Angular 6 component. Here is my setup: <kendo-grid [data]="view | async" [height]="533" (dataStateChange)="onStateChange($event)" (edit)="editHandler($even ...

Encountered a problem while attempting to create a new Angular project due to an unexpected termination of JSON input during parsing

Angular CLI: 10.0.4 Node: 12.18.3 npm : 6.14.6 Whenever I attempt to start a new angular project, I encounter errors that prevent the process from completing successfully. The installation of packages hangs indefinitely and eventually throws an erro ...

There was an issue encountered while trying to execute npm install, resulting in the error message: "This is a glitch

I am diving into the world of Angular and Node for the first time. I'm currently attempting to run a project that combines Angular with Neo4j, but encountering some issues along the way. When I initially tried to launch the project as is, after openin ...

Changes to the value of an Angular FormControl will automatically trigger changes in the entire formgroup

When attempting to validate the uniqueness of a user's email through an API call, I encountered a problem where any changes in form controls would trigger the value change. Below is my code: Errors(){ this.form01.valueChanges .subscribe((changed ...

Angular2 implementation of scroll spy feature for CKEditor

I have a file loaded in CKEditor with a side menu located outside the editor. I'm looking to dynamically highlight specific items in the side navigation as different sections of the document are scrolled through. details.component.ts focusFunction() ...