Is it possible for form controls to inherit from another form?

Two key elements make up my structure: The ParentComponent and ChildComponent:

parent.component.ts

<form #form="ngForm" (ngSubmit)="onSubmit(form)" novalidate>
        <input type="text" name="firstControl" [(ngModel)]="firstControl" />
        <input type="text" name="secondControl" [(ngModel)]="secondControl" />
        <child-component>
    </form>
    {{form.value | json}}
    

child.component.ts

<input type="text" name="thirdControl" [(ngModel)]="thirdControl" />
        <input type="text" name="fourthControl" [(ngModel)]="fourthControl" />
    

Currently, {{form.value | json}} displays

{ "firstControl": "", "secondControl": "" }
and is self-explanatory. However, my query is: Is there a method to inherit form controls from the ChildComponent? What is the correct procedure to achieve
{ "firstControl": "", "secondControl": "", "thirdControl": "", "fourthControl": "" }
for the ParentComponent? Is this achievable?

Answer №1

Recent Update:

It turns out there is a simpler solution:

import { FormsModule, ControlContainer, NgForm, NgModel } from '@angular/forms';

@Component({
  ...
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class ChildComponent {}

Additional Resources:

  • Angular2 nested template driven form

Previous Version Details:

It seems very much possible. For instance, you could integrate the following code within your

child.component.ts

import { NgForm, NgModel } from '@angular/forms';

@Component({
  selector: 'child-component',
  template: `
      <input type="text" name="thirdControl" [(ngModel)]="thirdControl" />
      <input type="text" name="fourthControl" [(ngModel)]="fourthControl" />
    `
})
export class ChildComponent {
  @ViewChildren(NgModel) ngModels: QueryList<NgModel>;

  constructor(@Optional() private ngForm: NgForm) {}

  ngAfterViewInit() {
    if (this.ngForm) {
      this.ngModels.forEach(model => this.ngForm.addControl(model));
    }
  }
}

Plunker Example

The Angular DI system grants us the ability to access the parent NgForm instance because the angular dependency resolution algorithm begins with the current node and traverses upwards through the element hierarchy. In my example, we can visualize the following hierarchy

              @NgModule providers
                    |
                  my-app
                    |
                   form
          /         |       \
   input[text] input[text] child-component

Therefore, when we request the NgForm token, Angular will search for it in the following sequence

child-component
     ||
     \/
    form
     ||
     \/
   my-app
     ||
     \/
  @NgModule

The NgForm directive is positioned on the form element, allowing us to access it. We can also access any token declared within the providers array of the NgForm directive. This principle applies to any node in the hierarchy.

For further information, check out Angular 2 - How does ng-bootstrap provide the NgbRadioGroup and NgbButtonLabel to their NgbRadio directive?

Subsequently, I manually included child NgModel directives within NgForm to ensure their seamless operation together.

Answer №2

Angular offers two types of forms: Template Driven and Reactive. If you are unable to achieve your desired functionality with Template Driven forms, you should explore Reactive Forms.

Generally, Reactive Forms involve creating a form object in the component and utilizing it in the template. While Angular claims this approach is more flexible and easier to test, some may find the syntax to be more complex.

For your parent component:

myForm: FormGroup; 

constructor(private fb: FormBuilder) { // <--- inject FormBuilder
  this.createForm();
}

createForm() {
  this.myForm = this.fb.group({
    firstControl: '',
    secondControl: '',
    thirdControl: '',
    fourthControl: ''
  });
}

Your parent template would resemble the following:

<form [formGroup]="myForm" novalidate>
  <input type="text" formControlName="firstControl" />
  <input type="text" formControlName="secondControl" />
  <child-component [parentFormGroup]="myForm">
</form>

The child component will accept the form group as an input, and its template will look like this:

<div class="form-group" [formGroup]="parentFormGroup">
  <input type="text" formControlName="thirdControl" />
  <input type="text" formControlName="fourthControl" />
</div>

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

gulp-tsc cannot locate the src directory

I am currently working on developing a .NET Core application using Angular2, but I keep encountering the following error: /wwwroot/NodeLib/gulp-tsc/src/compiler.ts' not found. I'm having trouble pinpointing what I might be missing. tsconfig.js ...

Angular2 Uniqueness Validator: Ensuring Data Integrity

Within my Angular2 form field, I am trying to ensure that the inputted value does not already exist. The challenge lies in accessing instance members within my custom validator function, codeUnique(). Upon execution, "this" refers to either FormControl o ...

Testing the output of a directive in a component unit test by simulation

One of the features I implemented in my Angular 5 component is utilizing the typeahead directive from ngx-bootstrap. Here's a snippet of how it's integrated: <input [(ngModel)]="inputted" [typeahead]="days" (typeaheadOnSelect)="select($ ...

What is the best way to bring in this interface from the React-Particles-JS library?

I have been attempting to segregate my parameters from my JSX within the react-particles-js library. I organize my parameters in an Object: let config = { "particles": { "number": { "value": 50 }, ...

Determine the outcome of the subscription using an if/else statement

I'm working on a function that needs to return a boolean value based on the result of an http post request. Here's what I have so far: checkPost(callRequest: boolean): boolean { console.log('START REQUEST'); if(call ...

The DAT GUI controls are mysteriously absent from the scene

Within a modal, I have set up a threejs scene with three point lights. All functions are exported from a separate file called three.ts to the modal component. The issue I am facing is that when I try to initialize DAT.GUI controls, they end up rendering ...

Tips for easily navigating Angular google Maps

<agm-map [zoom]="mapConfig.zoom" [styles]="mapConfig.styles" [latitude]="currLate" [longitude]="currLongi" > <agm-direction *ngIf="path" [origin]="path.origin" [destination]="path.destination" ...

Difficulty encountered when combining create-react-app with typescript and immutable.js

After realizing that create-react-app now supports typescript, I encountered some issues while trying to transfer my current codebase from react-scripts-ts. Most of my classes are based on Record and cannot be constructed anymore due to errors like: Cannot ...

Navigating through the directory to locate the referenced folder in a Types

Is there a way to declare a path to a referenced folder in order to have a more concise import statement using the @resources path? I am building from /server by running tsc -b app.ts The following long import statement works: import IEntity from &ap ...

The File Filter feature of Angular's ng2-file-upload is not functioning correctly for PNG files in the Internet Explorer

I am encountering an issue with the file uploader plugin ng2-file-upload when trying to upload a PNG file using Internet Explorer 11. For some reason, the PNG files are not being added to the queue, even though all other allowed file types work perfectly f ...

Instructions for arranging the mat-mini-fab to appear below, similar to how matBadge is displayed

Is there a way to display the mat-mini-fab button in the corner of another button, similar to the matBadge style? For example: https://stackblitz.com/edit/angular-prtfqp?file=src%2Fapp%2Fbutton-overview-example.html I am looking for a solution where I c ...

Struggles with embedding a table within a form while working with jQuery Mobile

Currently facing a problem trying to embed an HTML table inside a form in a jQuery Mobile environment. An error message pops up: Uncaught TypeError: Cannot read property 'not' of undefined The Chrome debugger points to this line in jquery.mobil ...

Implementing a Responsive Form on an Image Using Bootstrap

I am facing a challenge where I need to position a form on top of a Responsive Image. My goal is to ensure that the form is responsive as well and adjusts its size according to the image. As of now, the image is responsive but I am struggling to make the ...

I'm encountering an issue trying to apply array filtering with checkboxes using React hooks and TypeScript

Help needed! I'm facing an issue while trying to filter an array based on gender using checkboxes. The functionality works fine for the male checkbox but seems to fail when clicking on the female checkbox. Below is the code snippet from my App.tsx fil ...

I'm receiving an error message stating that 'This command is not available when running the Angular CLI outside a workspace,' even though I am in the correct folder

Upon starting my Angular project, which I cloned from GitHub and initiated using the command line "ng serve" or "ng serve -o", I encountered the following error: "Error: This command is not available when running the Angular CLI outside a workspace." My pr ...

What is the best way to incorporate the TUI image editor for Javascript into my Angular application?

Issue - I'm facing a challenge with my Angular application as I want to integrate Toast UI image editor. However, I am unsure about how to properly add the imports to app.module.ts in order to utilize it. Despite following the npm installation instru ...

What is the best way to receive a notification once the final observable has completed emitting its values?

In the past, we only made one call to the API reqFinanceDataWithFilters(req): Observable<any> { return this.http.post(env.baseUrl + req.url, req.filters) .pipe(map(this.extractResults)); } However, the response from this single request was a ...

I am not currently working on developing an angular application

Seeking assistance for the issue described below, as I have been struggling with it for three days. Any help would be greatly appreciated. Despite multiple attempts, the situation only seems to worsen with each try. The problem arises when attempting to ...

The whereabouts of the node_modules folder during the development phase

As I dive into Angular 2 app development, I encountered an issue. Installing node modules in each project folder using npm install seems to be taking up a lot of disk space and causing duplication across multiple projects. This led me to consider creating ...

Watching videos is quite a time-consuming process due to the long loading times

I recently created a website at , and I am facing an issue with the homepage video taking too long to play. While it works fine on a PC, it seems to load very slowly on mobile browsers. Any suggestions on how I can improve its loading speed? <video cl ...