Creating a component in Angular that utilizes multiple nested FormGroups

When attempting to nest multiple FormGroups, everything works smoothly if the template is not extracted into separate components.

For instance, the following example functions as expected:

Template

<form [formGroup]="baseForm">
  <div formGroupName="nestedForm1">
    <div formGroupName="nestedForm2">
      <input formControlName="nestedControl">
    </div>
  </div>
</form>

Typescript

this.baseForm = this.formBuilder.group({
  nestedForm1: this.formBuilder.group({
    nestedForm2: this.formBuilder.group({
      nestedControl: ["Default Value"]
    })
  })
});

However, when attempting to move "nestedForm1" and "nestedForm2" into separate components, issues arise beyond the first level of nesting.

To see an example and experiment with both approaches, you can visit the following link. You can toggle between the two methods by commenting out specific code segments in the "app.component.html" file.

Link to Example

Answer №1

One of the reasons is that the ControlContainer provider can be registered with various directives:

Directives for Template-driven Forms

  • NgForm
  • NgModelGroup,

Directives for Reactive Forms

  • FormGroupDirective
  • FormGroupName
  • FormArrayName

However, there might be instances where you expect it to always be FormGroupDirective, but in reality, in the parent component of the second control container is FormGroupName.

A more universal approach would be to use a common solution that works regardless of the type of parent ControlContainer:

viewProviders: [{
  provide: ControlContainer,
  useFactory: (container: ControlContainer) => container,
  deps: [[new SkipSelf(), ControlContainer]],
}]

Check out this Forked Stackblitz for reference

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

Encountered in the Angular library: NG0203 error stating that inject() should only be invoked within an injection context like a constructor, factory function, or field initializer

Having recently updated my Angular project from version 9 to 15, I encountered the following issue. Any assistance would be greatly appreciated as I have been struggling with it for over 2 weeks. The problem lies within app-lib.module.ts in the Angular li ...

The issue arises when attempting to drop elements from two lists with incorrect positions and mismatched coordinates

Angular 9 had a working version of this, which you can find here: https://stackblitz.com/edit/two-drop-list-problem-zp556d?file=package.json Now in the new Angular 14 version: https://stackblitz.com/edit/angular-ivy-1jvbnn?file=src%2Fapp%2Fapp.component ...

Can one mimic a TypeScript decorator?

Assuming I have a method decorator like this: class Service { @LogCall() doSomething() { return 1 + 1; } } Is there a way to simulate mocking the @LogCall decorator in unit tests, either by preventing it from being applied or by a ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...

Angular2 - Incorporating a New Attribute

I am working with the following Angular2 code: <ngx-datatable-column prop="id" name="ID"> <template ngx-datatable-cell-template let-row="row" let-value="value"> <a [routerLink]="['/devicedtls',r ...

Angular: Displaying data in a list format from a multidimensional array

My data structure is as follows: { 'TeamLeader': 'Andrew', 'subordinates': [{ 'Name': 'Daniel', 'subordinates': [{ 'Name': 'Stev ...

It takes two clicks for the text to change on the button in Angular

As a newcomer to angular, I am working on a quiz application where I've encountered an issue. When I click a button, it requires two clicks to function properly. The first click works fine, but subsequent clicks on the next and back buttons need to be ...

Replace the css variables provided by the Angular library with custom ones

Having an angular library with a defined set of css variables for colors applied to components, which are globally set like this: :root { -color-1: #000000; -color-2: #ffffff; ... } In my application utilizing this library, I need to override ...

Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for ...

Issue encountered while trying to determine the Angular version due to errors in the development packages

My ng command is displaying the following version details: Angular CLI: 10.2.0 Node: 12.16.3 OS: win32 x64 Angular: <error> ... animations, cdk, common, compiler, compiler-cli, core, forms ... language-service, material, platform-browser ... platfor ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

What are some methods for retrieving RTK Query data beyond the confines of a component?

In my React Typescript app using RTK Query, I am working on implementing custom selectors. However, I need to fetch data from another endpoint to achieve this: store.dispatch(userApiSlice.endpoints.check.initiate(undefined)) const data = userApiSlice.endpo ...

Setting up next-i18next with NextJS and Typescript

While using the next-i18next library in a NextJS and Typescript project, I came across an issue mentioned at the end of this post. Can anyone provide guidance on how to resolve it? I have shared the code snippets from the files where I have implemented the ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

Application of Criteria for Zod Depending on Data Stored in Array Field

I am currently working on an Express route that requires validation of the request body using Zod. The challenge arises when I need to conditionally require certain fields based on the values in the "channels" field, which is an array of enums. While my cu ...

Learning how to smoothly navigate to the top of a page when changing routes in Angular using provideRouter

Is there a way to make the Angular router automatically scroll to the top of the page when the route changes? In my previous setup using NgModules, I could achieve this with: RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'top' }) ...