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

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Merging Two mat-error Elements in Angular

I recently dived into the world of Angular by following their official tutorial. Curiosity got the best of me and I started experimenting with error handling using Angular Material when a user enters their email. I'm wondering if there's a way to ...

How to Retrieve ViewChild Element from within Input Component in Angular 2

Currently, I am utilizing ViewChild to target a specific HTML element within an Angular 2 component. My goal is to access this element from an Input field, but I am struggling with the correct syntax to correctly target the element in question. Below is th ...

Exploring LocalStorage Monitoring in Vue.js 2

How can I stay informed about any changes in Banana.vue? I have tried using addEventListener, @watch but it doesn't seem to be working... The index.vue file is importing both Apple.vue and Banana.vue In Apple.vue: localStorage.setItem('fruit ...

Encountering the "encoding" Module Error when Implementing Nextjs-13 with Supabase

I encountered an issue while trying to utilize Supabase for handling data insertion/retrieval from my form. Upon compilation, I received an error stating that the encoding module was not found. Despite attempting cache cleaning and re-installation of npm m ...

"Adjusting the size of a circle to zero in a D3 SVG using Angular 2

Trying to create a basic line graph using d3 in Angular 2 typescript. Below is the code snippet: import { Component, ViewChild, ElementRef, Input, OnInit } from '@angular/core'; import * as d3 from 'd3'; @Component({ selector: 'm ...

Tips on passing an object as data through Angular router navigation:

I currently have a similar route set up: this.router.navigate(["/menu/extra-hour/extra-hours/observations/", id]) The navigation is working fine, but I would like to pass the entire data object to the screen in order to render it using the route. How can ...

Enhance the MUI palette by incorporating TypeScript, allowing for seamless indexing through the palette

When utilizing the Material UI Palette with Typescript, I am encountering a significant issue due to limited documentation on MUI v5.0 in this area. Deep understanding of typescript is also required. The objective is to iterate through the palette and vir ...

Guide to releasing your Angular 6 library to npmjs along with a detailed README.md

I'm currently in the process of developing an Angular 6 library that I intend to share on npmjs. The library, named ng-as-multiselect-dropdown, is versioned on GitHub through the workspace project 'sample'. I used the Angular-CLI command &ap ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

Is it recommended to store SCSS and TypeScript files in the wwwroot folder in ASP.NET Core and Angular 2 development?

I'm struggling to understand where I should place my ts and scss files. The wwwroot folder is specifically for static files, but the ts and scss files are compiled. Should I recreate a similar folder structure both in wwwroot and outside of it, and th ...

Arranging Angular Cards alphabetically by First Name and Last Name

I am working with a set of 6 cards that contain basic user information such as first name, last name, and email. On the Users Details Page, I need to implement a dropdown menu with two sorting options: one for sorting by first name and another for sorting ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

Angular 6: Prevented Loading Resource Due to Content Security Policy: A script from self was blocked from being loaded on the page

Currently, I am developing a project in Angular 6 and everything seems to be running smoothly. Running the command ng --serve and building it using ng build results in no errors when deploying it on my local Tomcat Server. However, when attemptin ...

Does @angular/router have a similar function to ui-router's transition.from()?

I am currently in the process of updating an Angular application from ui-router to @angular/router (v6). There is a specific function that aims to retrieve the previous route. Below is the code snippet utilizing Transition from ui-router/core: const ...

Utilize an Angular pipe to convert numbers into easily readable fractions

Seeking help in creating a flexible Angular 5 pipe that can translate a number into a more readable fraction. For instance: 0,66 -> ⅔ 0,25 -> ¼ 1.25 -> 1 ¼ I have already started working on it but I want to enhance its flexibility: export ...

Ensuring Type Safety in Typescript

I have a specific requirement where I need to validate the structure of a request body to ensure it conforms to a predefined type. Is there a way or a package that can help achieve this validation? type SampleRequestBody = { id: string; name: string; ...

Identifying Similar Components in Angular 4: A Guide to Recognizing Rendered Elements

I am working with a clock.component.ts file and a dashboard where I need to display the clock multiple times based on the number of assigned runners for each user. For example, if a user has 3 assigned runners, I need to render the clock component 3 times. ...

Ways to address the issue of duplicated names in input fields

Currently, I am utilizing a React Hook Form hook known as useFieldsArray. This hook is responsible for rendering an array of fields, each containing an object with the data that will be transmitted via the input. One interesting feature is the ability to ...

"The process of logging in to Facebook on Ionic app speeds up by bypassing

I'm facing a minor issue with Facebook login in Ionic. I've tried using Async - Await and various other methods to make it wait for the response, but nothing seems to work. The login function is working fine, but it's not pausing for me to p ...