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

connecting and linking template content with an Observable

I have a CRUD page that needs to be updated after every operation. I have implemented Observable and the CRUD functions (specifically Add and Delete) are working fine, but I need to manually refresh the page to see the changes reflected. After trying to ...

Issues with the ionViewDidLoad() function?

Having some trouble implementing Email Authentication in my project. The method ionViewDidLoad is not being recognized. I also tried using the method ionViewWillLoad() but that didn't work either. Any ideas on what might be causing this issue? Here&a ...

What is the best way to utilize namespaces across multiple files in your program

I am currently working with TypeScript 1.6.2 and atom-typescript. In my project, I'm attempting to utilize namespaces across separate files: // Main.ts import * as _ from 'lodash' namespace Test { export var value = true } // Another.ts ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

How to conditionally apply a directive to the same tag in Angular 4

I am implementing angular 4 and have a directive in my template for validation purposes. However, I would like to first check if a specific condition is true before applying the directive. Currently, my code looks like this: <div *ngIf="groupCheck; els ...

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

Utilize an array of observables with the zip and read function

I'm struggling with putting an array of observables into Observable.zip. I need to create a function that reads values from this dynamically sized array, but I'm not sure how to go about it. Does anyone have any suggestions? import {Observable} ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

What is the best way to iterate over an array of objects?

I have an Array of Objects that I need to use in order to create an HTML Table: Array(5) 0: Object id: 4 name: Sand Jane address: Green Sand Street ... ... ... 1: Object 2: Object ... ... ... Currently, I am able to perform a search wit ...

Dynamic Setting of Content-Type Header (Multipart/Data) Through Http Interceptor

I have been trying to upload a CSV file using an HttpInterceptor as a middleware. Everything works fine for normal requests, but I need to modify the request header to 'multipart/data' specifically for CSV uploads. Below is the code snippet: ex ...

I encountered an eslint error when I was trying to configure Vue 3 + Quasar with a Firebase config.ts file. The error stated that there was an unsafe assignment of an `

Recently, I set up a new Vue 3 project with Quasar using the Quasar CLI. In order to store my firebase configuration, I created a new file called src/firebase/config.ts, which looks like this: // Import necessary functions from SDKs import { initializeApp ...

Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correct ...

Unable to employ a custom Typescript .d.ts file

Currently, I am delving into learning TypeScript and encountering a hurdle while attempting to define a class in a TypeScript definition file and then utilize it in a TypeScript file. The dilemma lies with a JavaScript "class" called "Facade," which serve ...

Testing Services in Angular4: A Comprehensive Guide

I'm new to Angular4 and need guidance on writing unit tests for a basic service I created. This service wraps an API call in the following manner: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable ...

Angular 4 scatter chart with multiple data points using Google charts

I'm currently developing a scatter graph in Angular 4 using ng2-google-charts from https://www.npmjs.com/package/ng2-google-charts It seems like this is essentially a wrapper for Google Chart Service. The graph looks great with a few values, but whe ...

What is the best way to utilize angular2 components based on their name using ngFor?

Check out the components I've created: app-widget-resume app-widget-my-courses-learner app-widget-my-courses-teacher app-widget-my-calendar app-widget-virtual-classes I want to populate my dashboard component, called my-dashboard, by util ...

Navigating the bitbucket pipeline to execute test cases for Angular 4 applications

Currently, I am facing an issue while integrating Bitbucket Pipeline for Angular 4. The problem lies in the fact that Chrome browser is not opening in the Bitbucket Pipeline console. My main objective is to figure out a way to execute test cases in the B ...

Is it possible to access the generic type that a different generic type inherits in TypeScript?

I've developed an interface specifically designed for types capable of self-converting to IDBKey: interface IDBValidKeyConvertible<TConvertedDBValidKey extends IDBValidKey> { convertToIDBValidKey: () => TConvertedDBValidKey; } My goal n ...

Oops! An error occurred: Uncaught promise rejection - invalid link found for ProductListComponent

I am currently in the process of learning Angular and Ionic, but I am feeling a bit confused as to where my mistake is. I have looked at other questions, but I still can't seem to figure it out. Can anyone provide some assistance? Perhaps someone has ...