Can Angular support nesting forms up to two levels deep?

In my Angular project, I am faced with the challenge of nesting a formgroup two levels deep to achieve a specific functionality. Here is the scenario:

I have several small formgroups all belonging to a common parentform. However, for a new page, I need to include one additional separate formgroup along with all the children of the existing parentform.

To streamline my code and avoid duplication, I am aiming to create a new parentform with two children: the separate formgroup and the original parentform.

The desired structure looks like this:

child formgroups \
                  ==> original parentform \
                                           ==> new parentform
                       separate formgroup /

Currently, I am importing both the original parentform and the separate formgroup in a similar manner by using methods like parentform.AddControl('separate', separate formgroup) and parentform.AddControl('original parent', parentform).

However, I am encountering an issue where the form updates correctly but the object in the body of the PUT request remains unchanged.

My question is whether it is possible to nest formgroups more than one level deep?

Answer №1

Absolutely, it is.

  form!: FormGroup;
  
  constructor(private formBuilder: FormBuilder) {
     // set up the form structure
     this.form = this.formBuilder.group({
      1: ['', Validators.required],
      2: this.formBuilder.group({
        2_1: ['', [Validators.required]],
        2_2:  ['', [Validators.required]],
      })
    });
  }

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <input type="text" formControlName="1" />

    <div class="form-group" formGroupName="2">
      <input type="text" formControlName="2_1" />
      <input type="text" formControlName="2_2" />
    </div>
  </div>

  <button [disabled]="loading" class="btn btn-primary">Submit</button>
</form>

and many more...

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 is the best approach to creating an array within my formgroup and adding data to it?

I have a function in my ngOnInit that creates a formgroup: ngOnInit() { //When the component starts, create the form group this.variacaoForm = this.fb.group({ variacoes: this.fb.array([this.createFormGroup()]) }); createFormGroup() ...

Tips for sending a variable to control a particular panel within an accordion in Angular 2

I have a collection of ngbpanels that are dynamically created using ngFor. I need to expand or collapse a specific panel based on certain conditions, but the ID I provide for the panel is stored in a variable. The code does not recognize the panel ID when ...

Using dangerouslySetInnerHTML in ReactJS can potentially strip away data attributes

After adding a data-test attribute to the a anchor tag within an HTML string and inserting it using dangerouslySetInnerHTML, I noticed that the data attributes are somehow being stripped out. Is there a way to prevent this from happening? These attribute ...

The installed local Angular version is outdated compared to the current project version

I've been having trouble customizing my Angular CLI because a package I need only works with an older version of Angular. Currently, my global Angular version is 15.2.9. However, when I create a new Angular project using ng new, the package.json shows ...

Referencing other styled-components in Typescript and React code bases

I'm attempting to replicate this code snippet found on https://styled-components.com/docs/advanced using TypeScript. const Link = styled.a` display: flex; align-items: center; padding: 5px 10px; background: papayawhip; color: palevioletred; ...

Angular is throwing an error when trying to create a new service: "Workspace must be loaded before it can be used."

Having trouble adding pusher.js to my angular.json file. After trying to create a new service, I encountered the following error: Error: Workspace needs to be loaded before it is used. Any tips on how to resolve this? I attempted to update the angular cl ...

Tips for showcasing with [displayWith] in Material2's AutoComplete feature

My API returns an array and I am using Material2#AutoComplete to filter it. While it is working, I am facing an issue where I need to display a different property instead of the currently binded value in the option element. I understand that I need to uti ...

Anticipated that 'styles' would comprise an array of strings in Angular2

Whenever I encounter this issue Uncaught Error: Expected 'styles' to be an array of strings. Below is my code example styleUrls:[ "../../styles/login.component.styles.scss" ], Interestingly, when I declare them in a similar manner but ...

Lack of MaterialUI Table props causing issues in Storybook

Currently, I am utilizing MaterialUI with some modifications to create a personalized library. My tool of choice for documentation is Storybook, using Typescript. An issue I have encountered is that the storybook table props are not consistently auto-gene ...

Modify the interface type whilst maintaining the structure of nested objects

In my system, I have a specific interface that outlines the structure of a NoSQL document schema. This includes strings, arrays, nested objects, and more. Here's an example representation: interface IStudentSchema { name: string; age: string; f ...

What is the best way to extract the inner text from an element within a QueryList<T>?

function addGoatToVaccinationGroup(goatObject: {earTag:string, id:number}){ for (let i = 0; i < this.vaccineQueue.length; i++){ if (this.vaccineQueue[i].earTag === goatObject.earTag){ this.vaccineQueue.splice(i, 1); ...

What is the reason behind hidden DOM elements appearing when I refresh the page?

When I refresh my webpage, I notice that the DOM elements I have hidden using ngIf are briefly visible before the actual state of my webpage loads. Why might this be happening? I am currently using Angular 8 version. <div *ngIf="!callInProgress ...

What purpose does a private property serve within the interface?

Given the following code snippet: class X { bar() { return "bar" } constructor(private readonly x: number){} } interface Y extends X { } const f = (y: Y) => { console.log(y.bar()); } f({ bar: () => "tavern"}); The code does ...

changing the order of items in a list when using ngFor

I'm currently working on setting up a list-group with list-group-items, but I've encountered a CSS issue caused by Angular when using ngFor on the list-group items. It seems like Angular automatically assigns the bootstrap classes .list-group-it ...

Having trouble connecting my chosen color from the color picker

Currently, I am working on an angularJS typescript application where I am trying to retrieve a color from a color picker. While I am successfully obtaining the value from the color picker, I am facing difficulty in binding this color as a background to my ...

Develop an interactive React sidebar with changing elements

I'm in the process of developing a sidebar for a project, with the goal of making it similar to tools like Confluence. This means that we need the ability to rearrange documents and create subdirectory structures by simply moving the documents, with ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

Angular 2 - illuminate modified data cell in table

Is there a way to highlight a table cell that has changed its value? <tr *ngFor="#product of products" (click)="onSelect(product)"> <td>{{product.productName}}</td> <td>{{product.price}}</td> </tr> Within the c ...

Accepting both array and non-array values in the setter function helps to address the issue of accommodating various

In my Angular component, I have an input that typically works with an array of strings: @Input() names: string[] <my-comp [names]="['Adam', 'Betty']"></my-comp> However, I would like to offer an alternative syntax where t ...

The exclusion of the type round-trip feature does not function properly in conjunction with generics

After coming across the commonly used type called Omit, defined as: type Omit<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>; This type is utilized to subtract types (the oppos ...