The parent component is failing to pass the form values to the child form group in CVA

My Angular application (view source code on Stackblitz) is running Angular 15, and it utilizes reactive forms along with a ControlValueAccessor pattern to construct a parent form containing child form groups. However, I am encountering an issue where the data is not being passed to the child when I designate it as a FormGroup in the parent's HTML template. On the other hand, if I label it as a FormControl, the data passes correctly and the child form can access it, but this approach results in an error:

ERROR Error: control.registerOnChange is not a function

Additionally, when annotating it as a FormControl, I am unable to retrieve the individual controls within the FormGroup.

In the provided code example, childGroupForm2 successfully receives the passed values, while childGroupForm does not.

My ideal solution would be to specify the FormGroup as a FormGroup and successfully pass the values from the parent component to the child.

Does anyone have insights into why this method is unsuccessful with FormGroups yet functional with FormControls?

Below is an updated version of the code for brevity:

// parent.component.html

<form [formGroup]="parentForm">
   <child-group [formGroup]="childGroupForm"> </child-group>
   <child-group [formControl]="childGroupForm2"> </child-group>
</form>  



// parent.component.ts

get childGroupForm(): FormGroup {
    return this.parentForm.get('childGroupForm') as FormGroup;
}

get childGroupForm2(): FormControl {
    return this.parentForm.get('childGroupForm2') as FormControl;
}

ngOnInit() {
    this.parentForm = this.fb.group({
      childGroupForm: this.fb.group({
        elementInput: 'Test1',
        elementsSelectionInput: 'Test2',
      }),
      childGroupForm2: this.fb.group({
        elementInput: 'Test3',
        elementsSelectionInput: 'Test4',
      }),
    });
}

Answer №1

A custom form control for your child-group is necessary, which is essentially a component that implements ControlValueAccessor. This custom form control is associated with a FormControl, not a FormGroup.

Therefore, in the parent component, your form should be structured as follows:

this.parentForm = this.fb.group({
  name: 'Test0',
  childGroupForm: this.fb.control({ 
    elementInput: 'Test1',
    elementsSelectionInput: 'Test2',
  }),
  childGroupForm2: this.fb.control({ 
    elementInput: 'Test3',
    elementsSelectionInput: 'Test4',
  }),
}); 

Your parent component template should look like this:

<form [formGroup]="parentForm">
  <child-group formControlName="childGroupForm"></child-group>
  <child-group formControlName="childGroupForm2"></child-group>
</form>

In my personal opinion, a custom form control should be utilized when managing a series of inputs or when more complexity is required. However, you can achieve similar results using a simple component with viewProvider as demonstrated here.

For an example utilizing a formGroup, please refer to the sample on StackBlitz.

//child
@Component({
  selector: 'hello',
  template: `<h1>Hello </h1>
  <div [formGroupName]="group">
    <input formControlName="elementInput"/>
    <input formControlName="elementsSelectionInput"/>
  </div>      `,
  styles: [`h1 { font-family: Lato; }`],
  viewProviders:[{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class HelloComponent  {
  @Input() group: string;
  
  constructor(){}
}

Then utilize the parent component like so:

  <form [formGroup]="form">
     <hello [group]="'childGroupForm'"  > </hello>
  </form>

  form=new FormGroup({
    childGroupForm:new FormGroup({
      elementInput:new FormControl(),
      elementsSelectionInput:new FormControl()
  
    })
  })

NOTE: In the provided example, new Form and new FormGroup are used instead of formBuilder, but the concept remains the same.

Answer №2

When setting up the form in your parent component, make sure to pass 'form' instead of 'group' to the childGroupForm:

ngOnInit() {
    this.parentForm = this.fb.group({
      name: 'Test0',
      childGroupForm: this.fb.form({ //update this.fb.group to this.fb.form
        elementInput: 'Test1',
        elementsSelectionInput: 'Test2',
      }),
      childGroupForm2: this.fb.form({ //update this.fb.group to this.fb.form
        elementInput: 'Test3',
        elementsSelectionInput: 'Test4',
      }),
    });
  }

Happy coding!

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

Using PHP to identify the origin of a JavaScript file on a webpage

I have been attempting to locate an embedded stream link from a certain webpage. After inspecting the source code of the page, I found the following snippet: <script type='text/javascript'> swidth='640', sheight='460';& ...

Running only failed tests in Protractor can be achieved by implementing a custom script that

I've encountered a problem in my JavaScript file where some of the test cases fail intermittently, and I want to rerun only those that have failed. Is there any feature or solution available that can help with this issue? It's quite frustrating a ...

Configuration object for Webpack is not valid

I encountered an error while using webpack that says: Invalid configuration object. Webpack has been initialized with a configuration object that does not conform to the API schema. - configuration.resolve has an unknown property 'extension&ap ...

To retrieve data from an AJAX response, you will receive an array in the form of a string

After requesting a list of posts submitted by users from my server, the response I received was a string containing an array of stdClass objects. If it had been an actual array, that would not have been an issue. However, it arrives as a string in the foll ...

find the repeated sequences of characters within the text

Trying to grasp a javascript string variable source; Is there an efficient technique to identify all REPEATED substrings of length around 20 characters (even if they overlap or include substrings of slightly different lengths)? An approach that could be ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

Encountering a TypeError stating that searchField.toLowerCase is not a function while employing hooks and redux in the

I've been working on a project to dive deeper into react. Recently, I made the switch to using hooks and attempted to integrate redux into it. However, I encountered an error that says: TypeError: searchField.toLowerCase is not a function After consu ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

Vue: Defining typed props interface including optional properties

I created a method that I want to be accessible on all my Vue instances, so I can use it in case of an error and display a specific error component. Similar to the functionality provided by vue-error-page. Since I am working with typescript, I now want to ...

Encountered issue with deploying Angular app to Firebase platform

After attempting to deploy my Angular 4 application on Firebase, I noticed that the setup process did not prompt me for any configuration details as outlined in various resources online. Despite running the 'firebase init' command and only being ...

Turn off the ability to drag on an HTML page

Need help with creating an HTML etch-a-sketch! I have a div container with multiple div elements inside it, all set up with CSS grid display. HTML structure: <div id="canvas"></div> To populate the canvas with div elements, I'v ...

What could be causing this code to continuously loop without end?

I've been scratching my head trying to understand why this code isn't working. var refP = []; var calculateDistance = function (p1, p2) { return dist(p1.x, p1.y, p2.x, p2.y); } while (refP.length < 24) { var point = { x: -1, ...

Is there a way to retrieve values from TextFields and Select elements by simply clicking on a button?

I am currently working on a project using react, redux, and material ui. I need to retrieve data from a TextField in order to make an order. The code snippet below showcases my current implementation: <Select value={product.color_set[0].title}> { ...

Update the CURLOPT_URL parameter to accept user input

As someone new to coding, I have a question about using the CURLOPT_URL function in PHP. How can I input a NIK number and retrieve data from this URL: ? Any help would be appreciated, thank you! php $curl = curl_init(); curl_setopt_array($curl, [ CU ...

Creating an interactive Table of Contents in Sharepoint using only JavaScript

Imagine you have a massive Sharepoint wiki page filled with various heading tags like H1, H2, H3, and H4 - now picture creating a dynamic Table of Contents using these tags. The goal is to categorize these tags by group and utilize the HTML <detail> ...

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...

Tips for implementing an if else statement in ReactJS while utilizing the useEffect hook

Below is the code snippet for returning a Plotly graph. I would like to display a message or alternative layout when there is no data available for the graph, such as showing "No data available". How can I achieve this? import React, { useEffect } from ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

Utilizing Regular Expressions in JavaScript to extract packages from an Android manifest document

When it comes to Android APK files, the manifest files play a crucial role: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp" android:versionCode="1" ...