Tips on looping through a dynamic FormControl using Angular2 and FormBuilder

I am facing an issue when trying to iterate over a dynamically generated FormControl in the HTML section. Instead of displaying the expected values, I am getting [object Object],[object Object] in the input field.

Here is the provided data structure:

{
    "security_groups": {
        "databaseName1": [{
            "destination": "10.0.8.1-10.0.8.255",
            "ports": "27000-27499",
            "protocol": "tcp"
        }, {
            "destination": "10.0.8.1-10.0.8.255",
            "ports": "27000-27499",
            "protocol": "tcp"
        }],
        "xyz": [{
            "destination": "10.0.8.1-10.0.8.255",
            "ports": "27000-27499",
            "protocol": "tcp"
        }]
    }
}

The JSON structure remains consistent but the naming can vary except for the key "security_groups."

In my controller, I have the following code snippet:

public form: FormGroup;
  public data: any;

  constructor(private _fb: FormBuilder) {
  }

  ngOnInit() {
    this.data = this.dataSet[this.key];

    this.form = this._fb.group({});
    Object.keys(this.data).forEach(name => {
      this.form.addControl(name, new FormControl(
        this.data[name], [<any>Validators.required, <any>Validators.minLength(1)]
      ));
    });

Upon checking the console, I see the structure as mentioned above.

Now, I need to iterate over these FormControls ("databaseName1" and "xyz") and display their names in the input fields.

Below is the current HTML code:

<form [formGroup]="form" (ngSubmit)="onSave(form)">
  <div *ngFor="let control of form.controls | keyVal; let i=index">

    control.log(control.key)

    <input class="form-control" [formControlName]=control.key>
  </div>
</form>

However, instead of the actual names, the input fields show [object Object],[object Object]. How can I resolve this issue?

Is there anything wrong with how the form is being created in the controller?

Thank you for your assistance.

Answer №1

By binding your input to the variables databaseName1 and xyz, you are displaying the value returned by calling toString on the passed property, resulting in [object Object].

If you wish to bind to the properties of a single object instead, consider removing validators from the example for clarity. The HTML implementation is left to your discretion.

ngOnInit() {
  this.data = this.dataSet[this.key];

  this.form = this._fb.group({});

  let self = this; // Define 'self' to capture 'this' due to multiple fat-arrow functions.
  Object.keys(this.data).forEach(name => { // Iterate through databaseName1 and xyz
    let array = self.data[name];
    array.forEach(item => { // Access objects within arrays referenced by databaseName1 and xyz
      self.form.addControl(name, new FormGroup({
        destination: new FormControl(item['destination']),
        ports: new FormControl(item['ports']),
        protocol: new FormControl(item['protocol'])
      }));
    });
  });
}

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

What could be the reason for the malfunctioning of the basic angular routing animation

I implemented a basic routing Angular animation, but I'm encountering issues where it's not functioning as expected. The animation definition is located in app.component.ts with <router-outlet></router-outlet> and two links that shoul ...

WebSocket connection outbound from Docker container fails to establish

Running a TypeScript program on Docker that needs to open a Websocket connection to an external server can be a bit tricky. Here is the scenario: ----------------------- ------------------------------ | My Local Docker | ...

Discovering the versatility of Typescript objects

I want to define a type that follows this rule: If the property container is present, then expect the property a. If the property item is present, then expect the property b. Both container and item cannot exist at the same time. The code I would expect ...

Managing Image Files in Node.js-Express with MongoDB and Displaying Them in Angular8 Interface

This Employee Management System allows for the uploading and storage of profile images of employees in an API server with a defined path. The implementation involves the following steps: Step 1: Making an API Server Request - Sample API Code router.get( ...

The type 'string' cannot be assigned to type 'ImageSourcePropType'

Context Attempting to utilize a SVG component in React Native with the xlinkHref property within an Image tag. The SVG file was converted into a React Native Component (TSX) using the tool provided at . While simple SVG icons have been successfully used be ...

What is the best way to iterate through all class properties that are specified using class-validator?

I have a class defined using the class-validator package. class Shape { @IsString() value?: string @IsString() id?: string } I am trying to find a way to retrieve the properties and types specified in this class. Is there a method to do s ...

hide elements only when there is no string to display in Angular2/Typescript

As I experiment with my javascript/typescript code, I've encountered an issue where a string is displayed letter by letter perfectly fine. However, once the entire string is shown, the element containing it disappears and allows the bottom element to ...

There seems to be an issue with the response type in the node.js environment

I am currently working on node.js and typescript, but I am encountering a minor issue. Below is the routeController I have created: public allUsers = (req: Request, res: Response) => { res.status(500).json({ status: "ERROR", ...

Guide to dynamically updating image URLs based on color selection in Angular when handling ngFor loop

component.ts // necessary imports have been included ngOnInit() { this.list = { 'eatList': [{ 'class': 'Fruits', 'color': ['Red', 'White', 'Black& ...

Setting a border on a specific column in ag-grid is a simple task that can help you customize

I have a table where the first set of columns differs from the rest. I am looking to emphasize this distinction by adding a vertical border on the right side of the specific column to highlight it both in the header and rows. Our setup includes using the ...

How can different styles be seamlessly combined when customizing Fabric components?

Imagine I am enhancing a Fabric component by adding custom styles and wishing to combine any additional styles passed in through its props. Here's the solution I've devised: const { TextField, Fabric , IButtonProps, mergeStyleSets } = window.Fab ...

Can you provide instructions on executing package dependencies using yarn in the command line? For example, is there a command similar to npx tsc init for initializing a npm

When utilizing yarn, the node_modules folder is not present. Instead, dependencies are stored in a .yarn/cache folder. I attempted to use yarn dlx tsc init and npx tsc init, but they did not achieve the desired result. There are various development depend ...

typescript mistakenly overlooked a potential undefined value in indexed records

In my code, I have defined an index-based type X. However, when using a non-existing key, TypeScript does not accurately infer the result type as ValueType | undefined. Is there a solution to correct this issue? type ValueType = { foobar:string; } t ...

After unsubscribing from RxJS timer, it starts again

Trying out a simple reflex-testing game here. The player has to click on the red rectangle when it turns green, and their score is displayed. However, the issue is that the timer restarts after clicking on the rectangle even though I tried using 'unsu ...

Turn off Inline CSS in Angular Universal

While rendering a site on the server with Angular Universal, the resulting page looks great. However, the source code of the pages contains an excessive amount of inline CSS (more than 50% of the document > 500kb), leading to slow download times especia ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

What steps can be taken to skip the email verification in Auth0 when updating a password by confirming the old password?

I am in need of creating a personalized page for changing passwords using auth0. I want the process to involve directly modifying the password without requiring an email with a password change link. Additionally, it needs to have a feature for confirming t ...

Struggled with setting up the WebSocket structure in typescript

Issue Running the code below results in an error: index.tsx import WebSocket from 'ws'; export default function Home() { const socket = new WebSocket('ws://localhost:1919/ws'); return ( <div>Home</div> ); } ...

Tracking events in Angular 4 using angulartics2 and Adobe Analytics: A step-by-step guide

I've been working on tracking page views in my Angular 4 application, specifically with Adobe Analytics. Currently, I am utilizing angulartics2 for this purpose. First step was adding the necessary script for Adobe Staging in my index.html page: &l ...

Finding a solution to this issue in Angular will consistently result in a false outcome

Can anyone explain why I keep getting the error message "This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap" whenever I try to compare charTypeEnum with ChartType.text? ...