Utilizing Nested ControlGroups in Angular2 rc1: A Comprehensive Guide

Seeking assistance with understanding the functionality of a control group. Attempting to implement something similar to this:

app.component.ts:

import { Component, OnInit } from "@angular/core";
import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from "@angular/common";
import { NestedFieldset } from "./nested.fieldset.component";

@Component({
  selector: 'my-app',
  directives: [
    NestedFieldset
  ],
  template: `
  <form (ngSubmit)="onSubmit()" [ngFormModel]="form">
    <nested-fieldset ngControlGroup="abFields" [parentForm]="form"></nested-fieldset>

    <label>field c: </label>
    <input placeholder="fieldC" ngControl="fieldC"/> <br>

    <button (ngSubmit)="onSubmit()">fancy submit</button>
  </form>
`})
export class AppComponent {
  form: ControlGroup;

  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      abFields: NestedFieldset.getControlGroup(fb),
      fieldC: ['']
    });
  }

  onSubmit(){
    console.log(" fancy was submitted")
    console.log(this.form.value)
  }
}

nested.fieldset.component.ts:

import { Component, Input } from "@angular/core";
import { TranslatePipe } from "ng2-translate/ng2-translate";
import { FormBuilder, ControlGroup, FORM_DIRECTIVES } from "@angular/common";

@Component({
  selector: 'nested-fieldset',
  directives: [
    FORM_DIRECTIVES],
  template: `
  <fieldset [ngFormModel]="parentForm">
    <label>field a: </label><input placeholder="fieldA"/> <br>
    <label>field b: </label><input placeholder="fieldB"/> <br>
  </fieldset>
  `
})
export class NestedFieldset {

  @Input()
  parentForm: ControlGroup;

  constructor() {}

  static getControlGroup(fb: FormBuilder) {
    return fb.group({
      fieldA: [''],
      fieldB: ['']
    });
  }
}

After submitting, fieldC is accessible, but having trouble accessing values from nested fieldset (fieldA and fieldB).

Any idea what could be causing this issue?

Take a look at the live example on plunker: http://plnkr.co/edit/EDqloxqd8xbByejEUZZx?p=preview

Answer №1

Here is the updated and fully functional plunker

In my approach, I consolidate all the form elements in one place (where the form is initially created) and then pass only the relevant group to the child component.

export class AppComponent {
  form: ControlGroup;
  result: any;

  // define form setup here  
  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      abFields: fb.group({
        fieldA: [''],
        fieldB: [''],
      }),
      fieldC: ['']
    });
  }
}

The template structure:

// passing only the abFields group
template: `
<form (ngSubmit)="onSubmit()" [ngFormModel]="form">
  <nested-fieldset [controlGroup]="form.find('abFields')"></nested-fieldset>

  <label>field c: </label>
  <input placeholder="fieldC" ngControl="fieldC"/> <br>

  <button (ngSubmit)="onSubmit()">fancy submit</button>
</form>
<pre><code>// using [ngFormControl]="controlGroup.find('..') for dynamic fields binding
@Component({
  selector: 'nested-fieldset',
  directives: [
    FORM_DIRECTIVES],
  template: `
  <fieldset >
    <label>field a: </label>
       <input placeholder="fieldA" [ngFormControl]="controlGroup.find('fieldA')"/> <br>
    <label>field b: </label>
       <input placeholder="fieldB" [ngFormControl]="controlGroup.find('fieldB')"/> <br>
  </fieldset>
  `
})
export class NestedFieldset {

  @Input() 
  controlGroup: ControlGroup;

  constructor() {}

}

See it live in action here

Important Note: Embracing the changes in the RC2 environment

https://docs.google.com/document/u/1/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub

Answer №2

Don't forget to include ngControls in the nested.fieldset.component.ts file:

 template: `
  <fieldset [ngFormModel]="parentForm">
    <label>field a: </label><input placeholder="fieldA" ngControl="fieldA"/> <br>
    <label>field b: </label><input placeholder="fieldB" ngControl="fieldB"/> <br>
  </fieldset>

Also, make sure that app.component.ts is using:

[parentForm]="form.find('abFields')"

instead of:

[parentForm]="form"

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

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 ...

What is the method for dynamically selecting generics from a function in a union type using Typescript?

Suppose there is a function defined as follows: type FooParams<Params extends unknown[], Result> = { name: string, request: (...params: Params) => Promise<Result> } const foo = <Params extends unknown[], Result>(params: FooParams ...

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

What are some creative ways to design the mat paginator in Angular?

Looking for tips on how to style Angular Material Paginator to match a Figma design? ...

Creating an object in AngularJS by merging data from three separate API calls

I am looking to develop a Jenkins dashboard using AngularJS. I am considering combining data from three different API calls to create an object that can be used in the HTML file with ng-repeat, but I'm not sure if this is the best approach. The desir ...

How to Invoke a TypeScript Function in Angular 2 Using jQuery

Using the Bootstrap-select dropdown in Angular 2 forms with jQuery, I am attempting to call a Typescript method called onDropDownChangeChange on the onchange event. However, it seems to not be functioning as expected. import { Component, OnInit, ViewChi ...

Is there a specific method for conducting a production build using AngularCLI rc.1?

Just recently upgraded to angular-cli version 1.0.0-rc1 by following the guidelines provided on the wiki. The application functions properly when I execute ng serve. Similarly, the app works as expected when I run ng build. However, encountering an issu ...

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...

Unable to access due to CORS restriction on Express server

Whenever I attempt to send a POST api request to my express server, I encounter the following error message. Access to XMLHttpRequest at 'localhost:8081/application' from origin 'localhost:8083' has been blocked by CORS policy: No &apos ...

Implementing route restrictions using $routeProvider

Within my MEAN application, I have implemented an authService module that includes an Auth factory featuring the authFactory.isLoggedIn function: // verify if a user is logged in // checks for existence of a local token authFactory.isLoggedIn = fu ...

Creating nested Angular form groups is essential for organizing form fields in a hierarchical structure that reflects

Imagine having the following structure for a formGroup: userGroup = { name, surname, address: { firstLine, secondLine } } This leads to creating HTML code similar to this: <form [formGroup]="userGroup"> <input formCon ...

Ways to transfer PHP output information using AngularJS

Welcome to my HTML page where I have added ng-app="myApp" and ng-controller="DashCtrl" <form action="" ng-submit="dashForm(dashdata)" method="post"> <input type="hidden" name="uid" ng-model="dashdata.uid" value="<?php echo $row ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

AngularJS Multi-select Dropdown Filter Logic

Thank you for taking the time to review my query. Currently, I am working on an AngularJS UI-Grid project where I have incorporated a Multi-select Drop-down Menu for the "First Name" column. However, I am facing challenges in implementing the logic similar ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

Encountering the message "npm ERR! missing script: start" following the update to .Net 3.0

Previously, the ASP.Net Core 2.2 code (upgraded from 2.1) did not include a start script in package.json. https://github.com/TrilonIO/aspnetcore-angular-universal/blob/master/package.json Upon upgrading to ASP.Net Core 3.0, it now requires a start script ...

Navigating the Angular (ng-Grid) testing waters: emitting an event with data using Jasmine

Assuming I have the following listener: $scope.$on('ngGridEventEndCellEdit', function(event, data){ var entity; if(data && data.targetScope && data.targetScope.row) { entity = data.targetScope.row.entity; } else { entity = event.t ...

Show a component on click event in Angular 4

Looking for a solution to create an event on a button click that triggers another component? When clicked again, the component should be reduced with a part always remaining visible. While I am currently using [ngClass]='hidden' within the same c ...

When using ng-repeat with Angular ui-bootstrap and tabs, the new tab will not be selected if there are no existing tabs present

To showcase the problem I'm facing, please refer to this link: http://codepen.io/pietrofxq/pen/ZLLJdr?editors=1010 Click on "remove tabs" and then on "add tab" The challenge at hand involves using a loop with ng-repeat to display tabs. At times, the ...