Strategies for efficiently looping through formbuilder.group control elements

JavaScript

formGroup = this.fb.group({});

constructor(private readonly formBuilder: UntypedFormBuilder){}

ngOnInit() { this.setFields(); }


setFields() {
 this.formGroup.addControl('username', this.fb.control('', Validators.required));
 this.formGroup.addControl('password', this.fb.control('', Validators.required));
 this.formGroup.addControl('email', this.fb.control('', Validators.required));
}

CSS

<ng-container *ngFor="let field of formGroup.controls">
  //display form control or component
 <input type="text" [formControlName]="field.name" class="form-control">
</ng-container>

I attempted to use ngFor, but it didn't work because the form builder group is an object and not an array. I understand there is a form array, however, that is not the solution I am looking for.

How can I loop through the form group controls?

Answer â„–1

Controls come in a specific type

controls: ɵTypedOrUntyped<TControl, TControl, {
    [key: string]: AbstractControl<any>;
}>

Therefore, you will need to utilize the keyvalue pipe to loop through it

<ng-container *ngFor="let control of formGroup.controls | keyvalue">
    {{ control.key }}   // control name
    {{ control.value }} // control value, this is not the actual value of the control itself              
                        // this is a property provided by the pipe to access the value of the object which should be of type formControl
                        // in order to access the actual value of the control, you must use control.value.value
</ng-container>

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

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...

Working with multiple observables in an array of properties using RXJS

I'm relatively new to using rxjs in my angular projects and I'm facing a challenge with a simple scenario. When making an http call to retrieve a group, it returns data including a list of "buddy ids", "genre ids", and a "region id". In order t ...

Tips on triggering a function when an Ionic or HTML event is initiated

I am facing a scenario on my HTML page where I need to display certain data when an if condition returns False, and execute a function when the condition returns true. However, I'm unsure about how to achieve this. <ng-container *ngIf="!(form.answ ...

Tips for presenting the cards in a professional layout

After creating a group of cards in angular using a for loop, I encountered an issue: <div class="row"> <div *ngFor="let dev_data of data" class="col-3"> <div class="card shadow"> <div class="card-body ...

Angular2 RC5 causing switchMap to fail in ngrx/effects

Recently in my Angular2 application, I've been utilizing ngrx/effects. However, with the release of RC5, I started encountering errors in my code. Here's a snippet: import { Injectable } from '@angular/core'; import { Effect, Actions } ...

Retrieve the value of a property within the same interface

Is there a way to access an interface prop value within the same interface declaration in order to dynamically set types? I am attempting something like this: export type MethodNames = "IsFallmanagerUpdateAllowed" | "UpdateStammFallmanager& ...

"Integrating PrimeNG with Angular in aspnetcore-spa template: A step-by-step guide

It feels like I spend more time setting up Angular than actually developing with it. There has to be a simpler way... :( Currently, I'm using the aspnetcore-spa template and creating projects with "dotnet new angular" version 1.0.3, which includes An ...

Why don't my absolute paths work on nested folders in React and Typescript?

Struggling to configure absolute paths in my React project, encountering challenges with nested folders and the use of @ prefix. Here's what I have set up in my tsconfig.json: { "compilerOptions":{ "baseUrl":"src", ...

Unable to find '.file.scss' in the directory '../pages'

I am currently in the process of migrating my Ionic 3 app to version 4. However, I have encountered an issue where some pages are not recognizing the SCSS file from the TypeScript component. @Component({ selector: 'car-id', templateUrl: &apo ...

Is it possible to integrate the extension library of three.js (including OBJLoader, SceneUtils, etc.) with Angular 6?

Attempting to implement the below code, however, it is not functioning as expected. npm install --save three-obj-loader import * as ThreeObjLoader from 'three-obj-loader'; const OBJLoader = ThreeObjLoader(THREE); let loader = new OBJLoader(): ...

The unsightly square surrounding my sprite in Three.js

I am attempting to create a beautiful "starry sky" effect using Three.js. However, I am encountering an issue where my transparent .png star sprites have a colored outline around them. Here is the sprite I am using: https://i.sstatic.net/2uylp.png This ...

I'm looking for the configuration of function definitions for the Jasmine npm module within an Angular project. Can

When a new Angular project is created, the *.spec.ts files provide access to Jasmine functions such as "describe", "beforeEach", and expect. Despite not having an import clause for them in spec.ts files, I can click on these functions and navigate to their ...

Updating the appearance of a table cell following the completion of table rendering

My json object includes a list of coordinates representing a board and another pair of coordinates to represent a turtle. Rendering the board is easy, but I'm struggling to figure out how to render the turtle. Should I use something like this: ang_ ...

What does the error message "JSON.parse: unexpected character at line 1 column 1 of the

In the process of developing a node.js module that involves importing a JSON file: const distDirPath = "c:/temp/dist/"; const targetPagePath = "c:/temp/index.html"; const cliJsonPath = "C:/CODE/MyApp/.angular-cli.json"; const fs = require('fs'); ...

React: Retrieved information, yet unable to access the properties of the object

After successfully fetching data from an API call and seeing the results in console, I am facing issues with accessing object properties and displaying them. interface Data { data: [] isLoading: boolean } function About() { const [ dataUser, ...

Is it possible to turn off the differentiation between null and undefined in TypeScript strict null-checking mode?

I've been in the process of upgrading a large TypeScript codebase to enforce strict null-checks. This codebase contains numerous types with optional properties: interface MyInterface { member1?: number; member2?: string; } Additionally, it define ...

What is the best way to pass the answerId in the action that I am dispatching, when the answerId is nested within an array object within another array object in

Reflect on the following: private listenToAnswerDeleted() { this.uiService.onGlobalEvent('ANSWER_DELETED').subscribe((response) => { this.store.dispatch(deleteAnswerAction({'answerId': })); }); } Upon receiving a respon ...

What is the reason behind Angular FormControl applying the 'disabled' attribute in the DOM but not the 'required' attribute?

After transitioning my form logic from the template to FormGroup & FormControl objects, I noticed that when a FormControl is disabled in Angular, the 'disabled' attribute for the field is automatically updated in the DOM. However, when I modi ...

Deliver router services for central Angular 2 elements

I am working on an ng2 app where I have the app/app.module and core/core.module. In the core modules, there are some modules that are used at the app top level and only once as mentioned in the official documentation. However, one of these modules requires ...

Intercepting Nested Requests in a Nest.js Application

Can you explain how to incorporate a nested interceptor in Nest.js? I currently have two interceptors: UsersInterceptor and PostsInterceptor UsersInterceptor: @Injectable() export class UsersInterceptor<T> implements NestInterceptor<T, Response& ...