Using FormBuilder to nest attributes

Is there a way to utilize Angular 2's FormBuilder to set nested attributes? For example:

this.form = formBuilder.group({
  name: ['', Validators.required],
  email: ['', Validators.required],

  address: {
     state: ['ca', Validators.required],   // <---- this gives an error
  }
});

Template:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <ion-item-divider color="light">Personal Data</ion-item-divider>
  <ion-item>
    <ion-label floating>Name</ion-label>
    <ion-input type="text" formControlName="name"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label floating>Email</ion-label>
    <ion-input type="text" formControlName="email"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label floating>State</ion-label>
    <ion-input type="text" formControlName="address.state"></ion-input>
  </ion-item>
</form>

Despite having the field state, an error is returned indicating it wasn't found.

This feature would greatly benefit me as I am working with a lengthy form that could use better organization.

Thank you in advance.

Answer №1

Sasxa had made progress in his answer, but he overlooked the fact that you were specifically looking for a solution to the template evaluation issue. This is why sharing the template was crucial.

To resolve the problem, you can enclose the address section of the template within an inconspicuous element like this:

<span formGroupName="address">
    <ion-item>
        <ion-label floating>State</ion-label>
        <ion-input type="text" formControlName="state"></ion-input>
     </ion-item>
</span>

When constructing the form, follow the suggestion given:

address: formBuilder.group({
   state: ['ca', Validators.required]
})

Further information about FormGroupName can be found in the documentation.

Answer №2

Consider trying out the following solution:

this.dataForm = this.formBuilder.group({
  fullName: ['', Validators.required],
  email: ['', Validators.required],

  addressDetails: this.formBuilder.group({
     country: ['US', Validators.required],
  }),
});

Include this code in your template:

<ion-input type="text" [formControl]="addressDetails.get('country')"></ion-input>

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

Presenting information using mat-table in Angular 2

Everything seems to be working fine with the code as I am able to display the data in mat-cards successfully. However, when I try to display it in mat-tables, I encounter index errors. I have made sure to import matTableDataSource, DataSource, CdkTableModu ...

Understanding the Contrasts: Effects of Destructive ( set() ) and Non-Destructive ( update() ) Updates in AngularFire2

Currently delving into the authentication process of https://github.com/codediodeio/angular-firestarter. This code snippet in the Authentication service of the repository is used to update user data by writing the user's name and email to a realtime ...

Can you explain how NGXS store manages its data storage? Is there a memory limit set for the NGXS store? And where exactly is the NGXS store memory located within the browser

Although I attempted to learn NGRX from their official site, I found myself lacking a clear understanding of where and how the data is stored within NGRX. Additionally, I could not find any information regarding the maximum limit of data that can be stor ...

(Vue with Typescript) Error: Component cannot be mounted as template or render function is not defined

Having trouble mounting component due to template or render function not defined. Hello everyone, I'm currently attempting to incorporate Typescript into my Laravel / Vue project. However, I've been encountering issues such as the following erro ...

Waiting for completion of two observables in RxJS/Angular 11 while also managing errors

Currently, I am facing the challenge of waiting for two requests to complete (observables) and performing certain actions. Here is what I need: Wait for both requests (observables) to finish If one of them fails - show one error message If both of them f ...

The function does not throw a compiler error when a parameter is missing

Currently utilizing TSC Version 2.4.2 Please take note of the following interface: interface CallbackWithNameParameter { cb: (name: string) => void } This code snippet: const aCallback: CallbackWithNameParameter = { cb: () => {} }; Manages t ...

Sending a string value from an object to a component by clicking a button in Angular

Within the HTML template of my component 'a', there is a button designed to redirect to another component: <button nbButton status="info" class="left" [routerLink]="['/centers', center.id, 'prices']">PRICES</button&g ...

Starting a new subscription once the current one expires

What is the process for starting a new subscription once an existing one ends using rxjs operators in Angular with 2 select statements? this.store.pipe( takeUntil(this.onDestroy$), select(getDatasetIsCreation), filter((datasetCreation) ...

Angular 2 is not compatible with ng2-charts

I've been attempting to utilize the basic chart of NG2-Charts from the website http://valor-software.com/ng2-charts/ I have copied and pasted the HTML section: <div> <div style="display: block"> <canvas baseChart [da ...

Angular Rick and Morty API Integration

I am working on iterating through objects retrieved from this URL: () to display them in a gallery of cards using *ngFor 1 This method is the only one I have found to render my data, but when I scroll down, it updates the URL for the new call 2 The issue ...

Tips for organizing nested properties within the field column definition of ag-grid

var data = [{ id: { id: "108662", absoluteUri:"abc.com", devicedisplayId: "045551" } devicename: "Printer" }] var columnDefs = [ { headerName: 'Device Id', field: 'id',filter: &ap ...

Using ngFor to connect input with the Algolia Places feature

I have implemented an Algolia Places input within an ngFor loop using Angular8. The issue I am facing is that the (change) event only works properly after typing in the input for the second time. While this is functional, it's not exactly the behavior ...

Unit testing in Angular: Using TestBed to mock asynchronous calls from injected services

Unit tests need to be written for the DataService as shown below: @Injectable() export class DataService { constructor(private config: ConfigService, private http: HttpClient) { } ..... someMethod(){ let apiUrl = this.config.get(&ap ...

Encountering a NoEmit error with .d.ts files when using Webpack, tsconfig, and dynamic imports

I'm struggling to grasp the interaction between webpack, tsconfig, and .d.ts files in my project. This is how my project structure looks: https://i.sstatic.net/ugdZM.png The ScriptsApp directory includes an @types folder structured like this: http ...

Error: Pump 3.0.1 encountered an unexpected character { causing a syntax issue

At approximately 10:30 PST on September 10, 2024, my ng build command suddenly started throwing an error during the execution of ng build. I am aware that I am using an outdated build and the immediate solution may be to upgrade everything to the latest ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

Contrasting the Appmodule and Pages module within Angular: A Comparison

After cloning this project, I noticed that it contains two types of modules: one inside the page and the other in the root directory. Directory Tree: https://i.sstatic.net/tjq0I.png App.module.ts import { BrowserModule } from '@angular/platform-bro ...

Is it possible to both break down a function parameter and maintain a named reference to it at the same time?

When working with stateless functional components in React, it is common to destructure the props object right away. Like this: export function MyCompoment({ title, foo, bar }) { return <div> title: {title}, ...</div> } Now ...

Angular 5 APP_INITIALIZER: Provider parse error - Cyclic dependency instantiation not possible

I am utilizing the APP_INITIALIZER token to execute a task upon page load before my Angular application is initialized. The service responsible for this functionality relies on another service located within my CoreModule. The issue at hand seems to be ab ...

Something went wrong trying to retrieve the compiled source code of https://deno.land/[email protected]/path/mod.ts. It seems the system is unable to locate the specified path. (os error 3)

Upon executing my main.ts script using deno, I encounter the following error message: error: Failed to retrieve compiled source code from https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcccbdbff8f918a86918f"& ...