Angular implementation of a reactive form including a child component

Upon inspection, I noticed that my father form component is displaying the values of nickName and name, but not the value of age. It seems that {{myFormFather.status}} does not recognize the component child. It's almost as if my child component is invisible - why is this happening?

Code from my-form-father.html:

<form [formGroup]="myFormFather" (ngSubmit)="onSubmit()">
    <input formControlName="nickName">
    <input formControlName="name">
    <my-form-child
            [age]="myFormFather">
    </my-form-child>
    <button type="submit"
            [disabled]="myFormFather.invalid">Save
    </button>
</form>

Code from my-form-father.ts:

myFormFather = new FormGroup({
    nickName: new FormControl(),
    name: new FormControl()
});

constructor(private fb:FormBuilder) {}

ngOnInit() {this.createForm()}

createForm() {
    this.myFormFather = this.fb.group({
        nickName: ['', [Validators.required],
        name: ['', [Validators.required]
    });
}

Code from my-form-child.html:

<div [formGroup]="ageForm">
    <input formControlName="age">
</div>

Code from my-form-child.ts:

@Input() ageForm = new FormGroup({
    age: new FormControl()
});

constructor(private fb:FormBuilder) {}

ngOnInit() {this.createForm()}

createForm() {
    this.ageForm = this.fb.group({
        age: ['', [Validators.required]]
    });
}

Answer №1

Greetings! I believe I have found the solution you were seeking.

Take a look at this Stack Blitz demo

The issue at hand: The form group passed from the parent was overwritten

@Input() ageForm = new FormGroup({
  age: new FormControl()
});

constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.createForm()
}

createForm() {
  // Beware, this code is replacing the FormGroup provided by the parent!
  this.ageForm = this.fb.group({
    age: ['', [Validators.required]]
  });

  // What you should have done instead is:
  // this.ageForm.addControl("age", new FormControl('', Validators.required));
}

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

Is there a way to obtain the current URL within the index.html file using Vue.js?

How can I retrieve the current URL in my index.html file using Vue.js? When using pure JavaScript in index.html, I am only able to obtain the URL of the initial page. In order to capture the URL of other pages, I need to refresh the page as the value of ...

Guide on utilizing a variable as a property in the `indexOf` function within a `map` function

I have a method that looks like this: retrieveUniqueValues(param) { var uniqueValues = []; uniqueValues = this.state.DataObjects.map(item => { if (uniqueValues.indexOf(item[param]) === -1) { uniqueValues.push(item[param]) ...

Node.js now supports ES6 imports using the `--experimental-modules` flag,

Experimenting with ES6 imports in node using the -experimental-modules flag. Here are the steps: mkdir testfolder cd testfolder npm init npm i --save testing-library touch script.mjs Next, add the following code to script.mjs: import { test1, test2, tes ...

Java script button click event is not functioning in IE 9 as expected

Here is the JavaScript code I am using: document.getElementById("<%= btnUpload.ClientID %>").click(); The functionality works flawlessly on all browsers except for Internet Explorer 9. What could possibly be causing this issue? ...

Can modifications be made to a page's source content variable using Ajax?

Can modifications be made to the source content of a page through Ajax loaded by a jsp include in the main jsp? If not, is it possible to refresh only that portion of the page (the jsp that loads some of the content) and have a portion of the content in t ...

What is the best way to retrieve a return string from an external program using XPCOM in Firefox?

Is there a way to execute an external program in XPCOM and retrieve the actual return string from it, instead of just the return code? I have researched nsICommandLine, nsICommandLineHandler, nsICommandLineRunner, and nsIProcess but it seems like none of ...

How to retrieve the path, route, or namespace of the current or parent component/view in a Vue.js application

I have been working on enhancing a sub-menu system for vue.js that dynamically populates based on the children routes of the current route. I recently asked a question about this and received a helpful answer. Currently, I am trying to further improve the ...

Having difficulties establishing a connection with the websocket URL generated by Spark Java

I'm currently working on creating a websocket using the sparkjava framework. Here is the code snippet for setting up the websocket: public final class MainWS { static Map<Session, String> USER_SESSION_MAP = new ConcurrentHashMap<>(); stat ...

PHP failed to receive Angular post request

My form consists of just two fields: <form name="save" ng-submit="sap.saved(save.$valid)" novalidate> <div class="form-group" > <input type="text" name="name" id="name" ng-model="sap.name" /> </div> ...

Converting JSON data from a PHP variable into a jQuery array: What you need to know

I attempted to retrieve addresses using the postcode and applied the getaddress.io site API with PHP. This resulted in a JSON dataset stored in the PHP variable $file. Now, I am tasked with converting this JSON result into a jQuery array. { "Latitude":-0. ...

Tips for individually assigning Fastify decorators within various plugins?

I'm encountering issues with typing decorators in two separate plugins (scopes): import Fastify, { FastifyInstance } from 'fastify' const fastify = Fastify() // scope A fastify.register((instance) => { instance.decorate('utilA&apo ...

What is the best way to access the Node.js HelloWorld File that I created with a .js extension?

I am currently going through the materials at "NodeBeginner.org". Despite my limited experience with command line, I am struggling to execute my first file. The only success I've had so far is running "console.log('helloworld');" by typing ...

Modifying the temp variable by assigning a new value to this.value in Javascript

Using a temporary variable, I initialize a THREE.Vector3 which is then passed into the creation of an object. object[i] = new Object(new THREE.Vector3(0,0,0)); Within the Object class, there is a variable called texture that gets assigned the new THREE.V ...

Refresh the table every couple of seconds

I need to regularly update a table every two to three seconds or in real-time if possible. The current method I tried caused the table to flash constantly, making it difficult to read and straining on the eyes. Would jQuery and Ajax solve this issue? How c ...

Integrating eBay API with Node.js

Hello, I am new to Node.js and I could really use some assistance with exporting console log data to an HTML page. I came across a helpful example on GitHub at this link: https://github.com/benbuckman/nodejs-ebay-api My current issue is that although I h ...

Is it necessary for me to use NG-IF / NG-SWITCH or should I opt for NG-SHOW & NG-HIDE instead?

I'm facing a frustrating dilemma because I am unsure of the best approach to take in this scenario. Below is the basic setup: I aim to display the current status of a movie, which will have different messages in the DOM based on its state. A movie ca ...

I'm having difficulty with the installation of the @angular/CLI package

npm ERROR 404: Package @angular/CLI@latest Not Found ** log: ** 0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\&b ...

Learn how to dynamically add a class to an element when hovering, and ensure that the class remains even after the mouse has

I'm facing difficulty with this task - when hovering over elements, an active class should be added to them. However, when moving the mouse to another section, the active class should remain on the last element hovered. Additionally, the first block s ...

When using React Ant Design, the form.resetFields() function does not trigger the onChange event of the Form.Items component

In my project, I am working with the Ant Design <Form> component and handling onChange events within <Form.Items>. Whenever the onChange event function evaluates to true, additional content is displayed dynamically. For instance, in the code s ...

React State-Driven Conditional Rendering

When selecting both the "Home Team" and "Away Team" options from two dropdowns, I need to display data for both teams in charts. You can view the prototype on codepen. Currently, I am only able to show one Line Component with a dataKey. How can I modify ...