Unable to retrieve the value from the nested formGroup

I am currently in the process of setting up nested formGroup fields using HTML code.

<form [formGroup]="userProfileForm" (ngSubmit)="bookUser()" class="form">
    <!-- userName -->
    <div class="form-group">
      <label for="userName">Name:</label>
      <input type="text" class="form-control" id="userName" formControlName="userName">
    </div>

    <!-- mobile -->
    <div class="form-group">
      <label for="mobileNumber">Mobile:</label>
      <input type="text" class="form-control" id="mobileNumber" formControlName="mobileNumber">
    </div>

    <!-- emailId -->
    <div class="form-group">
        <label for="emailId">Email id:</label>
        <input type="text" class="form-control" id="emailId" formControlName="emailId">
    </div>

    <!-- password -->
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="text" class="form-control" id="password" formControlName="password">
    </div>

    <!-- address -->
    <div class="form-group">
      <div formGroupName="address">
        <label for="city">City:</label>
        <input type="text" class="form-control" id="city" formControlname="city">

        <label for="state">State:</label>
        <input type="text" class="form-control" id="state" formControlname="state">

        <label for="zipCode">Zip Code:</label>
        <input type="text" class="form-control" id="zipCode" formControlname="zipCode">
      </div>
    </div>
    <button type="submit" class="btn btn-primary">Create Profile</button>
</form>

Below is the TypeScript code i have implemented...

ngOnInit() {
    this.userProfileForm=this.formBuilder.group({
      userName:['', Validators.required],
      mobileNumber:['', Validators.required],
      emailId:['', Validators.required],
      password:['', Validators.required],
      address: this.formBuilder.group({
        city:['', Validators.required],
        state:['', Validators.required],
        zipCode:['', Validators.required]
      })
    });
  }

When I attempt to print the city formControl value from the child formGroup, it does not display on the HTML. I have tried accessing the value through various methods such as:

(<FormGroup>this.userProfileForm.get('address')).get('city').value;
and
this.city=this.userProfileForm['controls'].address['controls'].city.value
but I still cannot retrieve the city field to show in the HTML. I also checked with
this.city=this.userProfileForm['controls'].address['controls'].city.valid
, which consistently returns false.

I have defined two model classes as well: UserProfile

import { Address } from "./address";

export class UserProfile{
    userName:string;
    emailId:string;
    password:string;
    mobileNumber:string;
    address:Address;
}

Address

export class Address{
    city:string;
    state:string;
    zipCode:string;
}

How can I successfully access the values within the nested formGroup? What am I missing here?

Answer №1

Everything seems to be in order. There appears to be a minor typing mistake where you wrote formControlname instead of formControlName. Remember to change the lowercase 'n' to an uppercase 'N'.

<div formGroupName="address">
        <label for="city">City:</label>
        <input type="text" class="form-control" id="city" formControlName="city">

        <label for="state">State:</label>
        <input type="text" class="form-control" id="state" formControlName="state">

        <label for="zipCode">Zip Code:</label>
        <input type="text" class="form-control" id="zipCode" formControlName="zipCode">
      </div>

Answer №2

Check out the solution provided by @Somdatt_Bhadvariya in response to How to use formControlName and deal with nested formGroup?. It was effective for my needs.

Typescript:

 this.myForm = fb.group({
        'fullname': ['', Validators.required],
        'gender': [],
        'address': fb.group({
            'street': [''],
            'houseNumber': [''],
            'postalCode': ['']
        })
    });

HTML:

  <form [formGroup]="myForm" >
       <div class="form-group">
          <label for="fullname">Username</label>
          <input type="text" id="username" formControlName="fullname" class="form-control">            
       </div>
       <div class="radio" *ngFor="let gender of genders">
          <label>
          <input type="radio" formControlName="gender" [value]="gender">{{ gender }} </label>
       </div>
       <div formGroupName="address">
          <div class="form-group">
             <label for="street">Username</label>
             <input type="text" id="username" value="street" formControlName="street" class="form-control">            
          </div>
          <div class="form-group">
             <label for="houseNumber">Username</label>
             <input type="text" id="username" value="street" formControlName="houseNumber" class="form-control">            
          </div>
          <div class="form-group">
             <label for="postalCode">Username</label>
             <input type="text" id="username" value="street" formControlName="postalCode" class="form-control">            
          </div>
       </div>
    </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

Guide on how to specify the return type for useMutation in the 'react-query' library

Here is the code snippet provided: const setFriendCode = (data: Params) => api({ data }) const [mutateSetFriendCode, state] = useMutation<Response, Params>( setFriendCode ) An issue arises with the type of parameters in the code. The compiler ...

Can a custom CSS be linked directly to the angular-cli.json file?

I'm trying to incorporate custom CSS into my angular-cli.json file, but I haven't been able to find a successful method. I attempted to use the following code: "styles": [ "styles.css", "http://site.test/mycss.css" ], However, it does ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

Ensuring Angular Reactive Forms: Validation for Non-Empty Nested FormArray with Display of mat-error

I'm currently working on a project using Angular's reactive forms and facing a challenge with a nested structure. I need to validate that a FormArray of files within another FormArray is not empty. Each groupFiles can have multiple groups, and ea ...

What is the best way to structure this React state container for modularity?

At my workplace, we have developed a state container hook for our React application and related packages. Before discussing what I'd like to achieve with this hook, let me provide some background information. Here is the functional code that's co ...

Importing the Ivy library component in Angular by specifying the module path as a string

Currently, I'm working with the latest Ivy release candidate. Scenario: I need to make multiple modules available for separate compilation and runtime loading using import statements, without relying on loadChildren from the router module. Backgroun ...

What steps are involved in creating animations on angular.dev?

I'm trying to recreate the animation on angular.dev. Specifically, I want to create a zoom effect on the Angular logo when scrolling. However, I'm unsure how to achieve this effect. If you visit this page , you'll see exactly what I mean. ...

Utilizing a Map with Angular's ngFor

Currently, I am working with Ionic 3, which utilizes Angular and TypeScript. My goal is to use ngFor with a Map type in my project. Below is what I have implemented so far: interface IShared_Position { lat: number; lng: number; time: number; ...

Angular does not include a particular parameter in the HTTP request

I am currently facing an unusual issue in Angular and Ionic 2 related to a specific provider I have set up. Here is the code snippet: getTransportations = function (category, maxResults) { let url = `${this.domain}/wp-json/gf/v2/forms/1/entries? ...

How can I effectively test the success of a form submission in next.js using jest for unit testing?

At the moment, I am in the process of developing a unit test for a registration form within my application. The main objective of this test is to ensure that the registration process can be executed successfully without actually saving any new data into th ...

Progressive File Upload in ASP.NET Core 2.0 and Angular 4.3: A Seamless Integration

Is there a way to utilize the latest Angular 4.3 HttpClient to handle file uploads and retrieval in an ASP.NET Core 2.0 Controller, all while providing live upload progress updates to the client? ...

Tips for preventing NPM EACCES: access denied error?

Whenever I try to run the command npm i -g npm, I keep encountering a plethora of errors, including: EACCES: permission denied and checkPermissions The suggested solution is: Please try running this command again as root/Administrator However, ...

I lost my hovering tooltip due to truncating the string, how can I bring it back in Angular?

When using an angular ngx-datatable-column, I added a hovering tooltip on mouseover. However, I noticed that the strings were too long and needed to be truncated accordingly: <span>{{ (value.length>15)? (value | slice:0:15)+'..':(value) ...

What are the steps to enable readonly or disabled functionality in Ionic 2?

Trying to make a field readonly or disabled in an ionic2 form: <ion-item> <ion-label fixed>Category <ion-icon name="ios-arrow-forward"></ion-icon></ion-label> <ion-input type="text" [disabled]="false" id="category_ ...

npm encountered an error while trying to fetch the requested package when running ng new app

I'm working on developing a new application using the ng new app command. Everything goes smoothly until reaching the final CREATE message below. At that point, it gets stuck for hours (literally) at the "Installing packages (npm)..." stage. Eventu ...

Dealing with arrays in Typescript and flattening them using the RX

Struggling with a problem involving RXJS transformation in an Ionic 2 application. My goal is to flatten a JSON file into objects, here is the simplified JSON structure: [{ "language": "it", "labels": { "name": "Hi", }, "t ...

Creating JSON files automatically when saving Angular 4 CLI projects in Visual Studio 2017

Just dipping my toes into Angular 4, I decided to start with VS 2017 for its integrated Angular support. NPM Task Runner has been handy for running NG BUILD alongside project builds. However, is there a method to see changes reflected in the JSON file wit ...

Utilizing Type Script 1.8 with Visual Studio 2017 for older projects: A step-by-step guide

After installing Visual Studio 2017, I encountered a TypeScript error when trying to run my project. It seems that VS 2017 is using TypeScript 2.1.5, while my application was designed for TypeScript 1.8. Is there a way to make VS 17 utilize TypeScript 1.8 ...

NodeJS and TypeScript are throwing an error with code TS2339, stating that the property 'timeOrigin' is not found on the type 'Performance'

I am currently working on a NodeJS/TypeScript application that utilizes Selenium WebDriver. Here is an excerpt from the code: import { WebDriver } from "selenium-webdriver"; export class MyClass { public async getTimeOrigin(driver: WebDriver ...

Strategies for efficiently loading 100,000 records into a table using Spring Boot on the server side and Angular on the front end

I am facing an issue with the speed of loading data from the back end to the front end without causing delays on the client side. I am using Spring Boot for the back end and Angular 7 for the front end. The problem arises when I submit a request from the f ...