Utilizing nested form arrays within Angular 8 for increased data manipulation

I am looking to develop a dynamic form builder using Angular 8.

In this form builder, I want to create inputs with dynamic validations. The input and validation fields must be customizable and dynamic.

Check out the Demo

This is how I initialized the form:

  
createItem(): FormGroup {
    return this.formBuilder.group({
      type: ['', Validators.compose([Validators.required])],
      label: ['', Validators.compose([Validators.required])],
      inputType: ['', Validators.compose([Validators.required])],
      name: ['', Validators.compose([Validators.required])],
      formName: ['', Validators.compose([Validators.required])],
      validations: this.formBuilder.group({
        name: [''],
        message: [''],
        validator: ['']
      })
    });
}

initialFormBuilder(): void {
 this.formGroup = this.formBuilder.group({
    formItem: this.formBuilder.array([this.createItem()])
});
}

validationItem(): FormGroup {
    return this.formBuilder.group({
      name: [''],
      message: [''],
      validator: ['']
    });
}

addItem(): void {
    this.items = this.formGroup.get('formItem') as FormArray;
    this.items.push(this.createItem());
}

addValidation(): void {
    this.validationItems = this.formGroup.get('formItem').get('validations') as FormArray;
    this.validationItems.push(this.validationItem());
}

Here's the HTML code:


<form [formGroup]="formGroup">
    <div formArrayName="formItem" *ngFor="let item of formGroup.get('formItem').controls; let i = index;">
        <div [formGroupName]="i">
            ...
        </div>
    </div>
</form>

When I added the line below, an error occurred:


<div formArrayName="validations" *ngFor="let validation of formGroup.get('formItem').get('validations').controls; let j = index">

I want users to be able to add new validations by clicking on a button. How can I fix this issue?

Answer №1

If you need to include an array of formGroup in the validation property, utilizing formArray is required.

Give this a shot:

component.ts

createItem(): FormGroup {
    return this.formBuilder.group({
      type: ['', Validators.compose([Validators.required])],
      label: ['', Validators.compose([Validators.required])],
      inputType: ['', Validators.compose([Validators.required])],
      name: ['', Validators.compose([Validators.required])],
      formName: ['', Validators.compose([Validators.required])],
      validations: this.validationItems
    });
  }

component.html

<div formArrayName="validations" *ngFor="let validation of item.get('validations').controls; let j = index">
        <div [formArrayName]="j">
          <div class="col-25">
            <label>Validation Name</label>
            <input placeholder="Validation Name" formControlName="name" />
          </div>
          <div class="col-25">
            <label>Validation Message</label>
            <input placeholder="Validation Message" formControlName="message" />
          </div>
          <div class="col-25">
            <label>Validator</label>
            <input placeholder="Validator" formControlName="validator" />
          </div>
        </div>
 </div>

Example

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

Loading textures for cubes using Three.js TextureLoader and CubeGeometry

I am currently learning threejs and I am trying to apply 6 different textures to each side of a cube. I initially achieved this using loadTexture. var material3 = new THREE.MeshPhongMaterial( {map: THREE.ImageUtils.loadTexture('textures/ps.png') ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

Unable to register click event, encountering an error message stating, "co.console.log() is not a function."

I've been attempting to create a button that navigates to another page while passing an object in the parameters. However, I keep encountering an error message: "co. is not a function." It's perplexing because I receive the same error when tr ...

Is implementing an API necessary for handling this basic event in Express JS?

Lately, I've been encountering challenges with the backend, particularly when working with Express JS. I realize that part of the problem might be my own misunderstanding - assuming that Express JS is a framework generator for MVC or solely for authen ...

Encountering a Problem with Angular 2 RC HTTP_PROVIDERS

I recently upgraded my Angular 2 application to the RC version. Everything was working smoothly until I included HTTP_PROVIDER and created a service.ts file. However, now I am encountering an error: (index):14 Error: SyntaxError: Unexpected token <( ...

What is the best way to integrate Sass into a Create-React-App project that is using TypeScript

After setting up a new project using create-react-app and typescript, I included a sass file in my project as per the documentation (which mentioned built-in support for sass files). However, when trying to compile, I encountered the following error relate ...

Tips for styling a mat-checkbox correctly

I'm working on customizing the appearance of a mat-checkbox (material2) to meet the following specifications: Always display a black border (#000000), regardless of whether the checkbox is checked or not When the checkbox is checked, show a white ti ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...

When an answer is provided in Inquirer.js, pressing Enter is causing the process to terminate

Currently, I am working on creating a Command Line Interface (CLI) using the NPM package called Inquirer. It has been a useful tool so far, but I have encountered an issue. The interface functions correctly in terms of posing questions to the user, but onc ...

Retrieving subscriber count from Feedburner using jQuery and JSON

Is there a way to showcase the total number of feedburner subscribers in a standard HTML/jQuery environment without using PHP? The code snippet should be functional within a typical HTML/jQuery page. Perhaps something along these lines: $(document). ...

What is the method to execute jQuery code after the completion of a fade out effect?

I am attempting to fade out a div upon click while also adjusting some CSS properties. The problem I am encountering is that the CSS properties change during the fade out transition, instead of after it has completed. I would like the values to change onc ...

Guide to utilizing the v-else directive within a v-for loop in Vue.js

After successfully looping through the data and filtering it, I have implemented a v-if condition to display only the necessary matches. However, when attempting to use v-else to handle cases where no matches are found, the loop continues even for non-mat ...

Vue js has a feature that enables users to input numbers with precision up to two decimal places

Currently facing an issue where I need to restrict input to no more than 2 decimal places. I came across a solution in a thread on Stack Overflow which addresses this using jQuery: JQuery allow only two numbers after decimal point. However, I am looking ...

Having some trouble getting this jsfiddle to function properly on my local machine. Any suggestions?

I'm having trouble with this jsfiddle. It works perfectly for me, but when I try to replicate it, nothing happens when I press the button. Can anyone help? http://jsfiddle.net/KPEGU/1850/ Here is the code snippet: <html> <head> <ti ...

Add a CSS class to a different element when hovering

I have the following HTML structure: <div class="container"> <div class="list-wrapper"> <ul> <li class="item-first"> </li> </ul> </div> <div class="description-wrapper"> <d ...

Issue with Angular 2 Observable not triggering the complete function

I've been experimenting with the hero app tutorial for Angular 2 and currently have this Component set up: import { Component, OnInit } from '@angular/core' import { Subject } from 'rxjs/Subject'; import { Hero } from "./hero"; im ...

What is the best way to modify the attributes of an object within the state?

Although I've been working with the React framework for a few weeks now, I still find myself surprised by new challenges on a regular basis. Currently, I am focused on developing the login/game lobby/server lobby for a group project game. The concept ...

Strangely peculiar glitch found in browsers built on the Chromium platform

During a school assignment, I'm attempting to adjust the width of a button using Javascript. Below is my code: const button = document.querySelector("button"); button.addEventListener("click", () => { console.log(button.offsetWidth); butto ...

A guide on invoking a Struts 2 action with a different parameter for each row in a jQuery DataTable

Currently, I am working on a JAVAEE project that involves the use of Struts 2 and jQuery DataTable. In this project, I need to add a link with each row in the DataTable that will call an action based on the row's ID. Below is the HTML code for this s ...

Utilizing jQuery to dynamically pass parameters to the YouTube API

When making a request to the YouTube API, I am structuring it as follows: $.get("https://www.googleapis.com/youtube/v3/channels", { part: "contentDetails", id: "somestring", key: "MY-API-KEY" } /*, ...*/ ) A hidden field contains the value id ...