Creating a form with multiple components in Angular 6: A step-by-step guide

I'm currently working on building a Reactive Form that spans across multiple components. Here's an example of what I have:

<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
   <app-names></app-names>
   <app-address></app-address>
   <app-phones></app-phones>
   <button type="submit">Submit</button>
</form>

However, when I attempt to submit the form, I receive an empty object.

Here's the Stackblitz link for reference

Answer №1

Implement the following updates

1.Consolidate all components under one FormGroup instead of creating separate ones for each component.

2.Ensure you pass the @Input for FormGroup as intended.

3.Eliminate the use of FormBuilder in the child component.

app.component.html

<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
    <app-names [myForm]="myForm"></app-names>
    <app-address [myForm]="myForm"></app-address>
    <app-phones [myForm]="myForm"></app-phones>
    <button type="submit">Submit</button>
</form>

address.component.ts

import { Component, OnInit, Input} from '@angular/core';
import { FormControl, FormGroup,FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.css']
})
export class AddressComponent implements OnInit {

  @Input() myForm: FormGroup;
  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.myForm.addControl("homeAddress" , new FormControl());
    this.myForm.addControl("officeAddress" , new FormControl());
  }

}

Apply similar modifications to other components as necessary.

Answer №2

If you prefer to avoid using @Input, there is another approach you can take:

import { Component, OnInit } from '@angular/core';
import {
    FormControl,
    ControlContainer,
    FormGroupDirective
} from '@angular/forms';

@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.css'],
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
     }
  ]
})
export class AddressComponent implements OnInit {
  constructor(private parent: FormGroupDirective) {}

  ngOnInit() {
    const myForm = this.parent.form;
    myForm.addControl("homeAddress", new FormControl());
    myForm.addControl("officeAddress", new FormControl());
  }
}

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

Monitor checkbox status to trigger confirmation dialog

My goal is to prevent the checkbox from changing if 'NO' is clicked in a dialog. The dialog pops up, but I can't figure out how to wait for it to close before allowing the checkbox change. I've attempted using Promises and doing everyt ...

Enhance Material UI with custom properties

Is it possible to add custom props to a Material UI component? I am looking to include additional props beyond what is provided by the API for a specific component. For example, when using Link: https://material-ui.com/api/link/ According to the document ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...

Tips for personalizing your Compodoc Angular documentation

I've been experimenting with adding extra side navigation menus to the current compodoc documentation. Here's an example of how I tried to accomplish this: menu-wc.js <li class="link"> <a href="dependencies.html" data-type="chapte ...

Guide on Creating a Custom Property within the Same Component in Angular 2

Having trouble defining a custom property called count. When I try to bind it, I get an error saying: Can't bind to 'count' since it isn't a known property of 'p'. How can I fix this issue and successfully make count a custom ...

Angular Universal in combination with AngularFire server experiences a hanging issue due to the first() pipe

I am currently developing an angular/firestore application that requires SSR capabilities. I have integrated angular universal into the project and everything seems to be functioning properly until I utilize the first() pipe on any of the firestore calls, ...

Is there a way to incorporate a loading spinner into a MaterialUI DataTable without having to specify a fixed height for the parent component?

Currently, I am using a MaterialUI DataTable with the following setup: <div style = {{height: 300}}> <DataGrid loading={true} getRowHeight={() => "auto"} getEstimatedRowHeight={() => 250} ...

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

What could be causing Next.js to re-render the entire page unnecessarily?

As a newcomer to Next.js, I am trying to develop an app where the header/navbar remains fixed at all times. Essentially, when the user navigates to different pages, only the main content should update without refreshing the navbar. Below is the code I have ...

What is the process for implementing mandatory field validation on a group of checkboxes?

Looking for assistance with Angular 2 Checkbox Selection: Check out the updated code snippet below: HTML <b><label *ngFor="let type of topics;let i=index" class="checkbox-inline"> <input type="checkbox" id="{{'ch ...

How can PrimeNG PIE chart values be displayed by default instead of only on hover over the slice?

front end <td> <div class="p-col-8 ui-toolbar-group-right"> <button pButton type="button" icon="pi pi-search" (click)="populate_charts()"></button> </div> </td> TS-File ...

Can someone guide me on finding my staticwebapp.config.json within Azure Devops for deploying Azure Static Web Apps during a release?

After setting up a pipeline to build the artifact for my Angular application, I encountered an issue with deployment where specific URLs would redirect me to a 404 error page. This problem seems to be related to the configuration in staticwebapp.config.jso ...

Looking to create a dynamic Angular reactive form using API response data? Seeking guidance on how to achieve this? Let's

[ { "name": "jkjk", "firstName": "hgh", "lastName": "ehtrh", "replytype": "svdv", "prodCode": "svv", "execu ...

Experiencing problems with npm installation while trying to compile Angular2 source code

I am trying to compile angular2 source code on my Windows 8.1 x64 development machine. The versions of Node and Npm I have are as follows: Node version 5.1.0 Npm version 3.3.12 1) Successfully cloned the repository 2) Executed bower install command - S ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...

I need a way to call a function in my Typescript code that will update the total value

I am trying to update my total automatically when the quantity or price changes, but so far nothing is happening. The products in question are as follows: this.products = this.ps.getProduct(); this.form= this.fb.group({ 'total': ...

The statement 'typeof import("...")' fails to meet the requirement of 'IEntry' constraint

When trying to run npm run build for my NextJS 13 app, I encountered the following type error: Type error: Type 'typeof import("E:/myapp/app/login/page")' does not satisfy the constraint 'IEntry'. Types of property 'def ...

Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator. app.component.html <app-child [myVariable]="myVariable"></app-child> app.component.ts @Component(...) export class AppC ...

Exploring the functionality of Array.prototype.includes() in Angular 7 with PhantomJS testing

While testing components in my Angular application, I noticed that unit tests utilizing Array.prototype.includes() are successful in Chrome but fail when executed with PhantomJS. I found some suggestions in the responses to this question related to a simi ...