Nested component in reactive forms not functioning as expected

I've been experimenting with creating nested reactive form components. Specifically, I'm working on a reusable input component for my app within a reactive form. How can I dynamically communicate with nested components in Reactive forms?

Despite my efforts, I keep encountering an error:

formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class)

Parent HTML

<form [formGroup]="disciplineForm">

      <app-input-multilang [labelName]="Title" (childToParent)="update($event)" ></app-input-multilang>

    </form>

Reusable comp: app-input-multilang HTML

<ng-container>
  <div class="form-group">
    <label for="discipline">{{Title}}</label>
    <div class="input-group">
      <input type="text" class="form-control" formControlName="control.name" id="discipline" required />
      <div class="input-group-append">
        <button class="btn btn-default active" type="button">de</button>
        <button class="btn btn-outline-secondary" type="button">en</button>
      </div>
    </div>
  </div>
</ng-container>

Reusable comp: app-input-multilang TS

import { Component, OnInit } from '@angular/core';
import { ControlValueAccessor,FormControl, FormGroup, Validators, NG_VALUE_ACCESSOR,NG_VALIDATORS, } from "@angular/forms";

@Component({
  selector: 'app-input-multilang',
  templateUrl: './form-input-multilang.component.html',
  styleUrls: ['./form-input-multilang.component.scss'],

})
export class FormInputMultilangComponent implements OnInit {



  constructor() { }

  ngOnInit() {
  }

}

Answer №1

When dividing a formGroup using child elements, you have the option to pass either the formGroup itself or the control. Take a look at an example on stackblitz

Your child component can be structured as follows:

<div [formGroup]="formGroup">
  <input formControlName="discipline"/>
</div>
//With @Input()
@Input() formGroup:FormGroup

As for the parent component:

<form [formGroup]="myForm">
  <child [formGroup]="myForm"></child>
</form>
<pre>
  {{myForm?.value|json}}
</pre>

Alternatively, you can choose to pass only one control.

The child component structure would then be:

<div >
  <input [formControl]="formControl"/>
</div>
//With @Input()
    @Input() formControl:FormControl

And the parent component would change to:

<form [formGroup]="myForm">
  <child2 [formControl]="myForm.get('mycontrol')"></child2>
</form>

Answer №2

Don't forget to include the formGroup directive in your child component. Although you've declared a form named cForm in your child component, you haven't added the formGroup directive to your child component's HTML. Make sure to add the formGroup directive like this:

 <ng-container>
  <form [formGroup]="cform">
     <div class="form-group">
  <label for="discipline">Discipline</label>
  <div class="input-group">
  <input type="text" class="form-control" formControlName="cname" id="discipline" required />
  <div class="input-group-append">
    <button class="btn btn-default active" type="button">de</button>
    <button class="btn btn-outline-secondary" type="button">en</button>
      </div>
     </div>
    </div>
  </form> 
</ng-container>

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

"The ion-label in Ionic2 is cutting off some of the text and not displaying it

I'm currently facing an issue with ion-label inside ion-item. The description is not properly displaying and instead, it shows dot-dot.. ..I need the entire text to be visible. Is there any solution available? <ion-card *ngFor="let product of prod ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

What is the process for dynamically loading a component by its name in Angular 2?

I am currently incorporating dynamic loading of angular components in my application by using the following code snippet. export class WizardTabContentContainer { @ViewChild('target', { read: ViewContainerRef }) target: any; @Input() TabCont ...

What is the best way to extract data from Azure Data Lake and showcase it within an Angular-2 interface?

I am facing a challenge where I need to retrieve files with content from Azure Data Lake and display them in an Angular-2 Component. The issue is that when using the List File Status() method, I am only able to obtain file properties, not the actual conten ...

Angular 2 integration for Oauth 2 popup authorization

I am in the process of updating an existing Angular application to utilize Angular 2. One challenge I am facing is opening an OAuth flow in a new pop-up window and then using window.postMessage to send a signal back to the Angular 2 app once the OAuth proc ...

What is the best way to position a material icon to the right of an input field?

Currently, I am using a mat auto complete text box with a search icon that is aligned to the left of the input. I am looking to align this search icon to the right instead. Can anyone provide assistance on how to achieve this? <mat-form-field floatLa ...

From where does the require.js file originate?

Currently, I am learning Angular 2 from the tutorial available at https://github.com/pkaul/maven-typescript-example. Once I proceed with the 3rd step (mvn jetty:run), a runnable war folder is generated in the example-webapp/target directory. However, I ha ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

The PWA software encountered an issue where the checkForUpdate function never resolved

Despite my efforts, I have encountered an issue while working with the PWA for our application. The checkForUpdate and versionUpdates methods do not seem to resolve to any values. constructor( appRef: ApplicationRef, updates: SwUpdate, ) { ...

Issue encountered when attempting to assign an action() to each individual component

I'm facing an issue with the button component I've created. import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-button', template: ` <ion-button color="{{color}}" (click)="action()"&g ...

Ensure that only numbers with a maximum of two decimal places are accepted in Angular 2 for input

On my webpage, there are several input boxes where users can enter numbers. I need to prevent them from entering more than two decimal places. Although I tried using the html 5 input Step="0.00", it didn't work as expected. I am open to any TypeScri ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

Using Typescript with Momentjs: 'String type cannot be assigned to Date type'

Up until now, my approach to utilizing the momentjs library was as follows: import * as moment from 'moment'; // import moment. @Component({..}); export class TestClass { lastUpdated = Date constructor(private myService: MyService){ this ...

Having difficulty grasping the concept of a component in Angular that utilizes a service which incorporates the HttpModule

I just started learning Angular and I'm grappling with a testing issue. After studying how the framework functions, I noticed that a component using a service which incorporates HttpModule requires the HttpModule to be imported in the component test ...

How to Retrieve Properties from Child Elements in NativeScript ngFor Directive

Working with a dynamically generated checklist in Angular/Nativescript: <StackLayout *ngIf="assessment"> <StackLayout *ngFor="let instance_item of assessment.exam_instance_items; let i= index"> <ns-examitem [attr.id] ...

Unusual conduct exhibited by a 16th version Angular module?

I've created a unique component using Angular 16. It's responsible for displaying a red div with a message inside. import { ChangeDetectionStrategy, Component, Input, OnInit, } from "@angular/core"; import { MaintenanceMessage } ...

What steps should I take to resolve the npm run build error in my Angular application when deploying it with a server in Visual Studio Code?

When attempting to build my application using the npm run build --configuration production command, I encountered the following errors that I am unsure how to address. Being new to utilizing npm build commands, I seek assistance in resolving this issue. n ...

Test for comparing objects partially using Jasmine Array

Is there a specific method in jasmine for checking if an array partially matches another array by comparing objects? Considering that the arrays could potentially contain large amounts of data from test files, is there a way to avoid comparing each indivi ...

One way to display a table is by populating it with data from an API. If the table does

Within my Angular 6 application, there exists a table that displays data fetched from a web api. Additionally, I have incorporated some ngIf containers. One of these containers is programmed to exhibit a message in case the web api data turns out to be emp ...