Tips for updating the selected option in a nested reactive form in Angular?

Class User is defined as follows:

export class User {
 name: string
 details: Details;
}

Class Details is defined as follows:

export class Details {
country: Country;
major : Major;
}

Class Major is defined as follows:

export class Major{
department : string;
subject : Subject;
}

The form structure is created as follows:

   userForm : FormGroup;
    
   constructor(private fb: FormBuilder){}

   ngOnInit(): void {
    this.createUserForm();
  }
  
  
  createUserForm() {
    this.userForm = this.fb.group(
      {
        name:new FormControl(null, Validators.required),
        details: this.fb.array([this.createDetailsForm()])
      }
    );
  }

  createDetailsForm(): FormGroup {
     return this.fb.group({
      country:this.createCountryForm(), 
      major:this.fb.array([this.createMajorForm()])
    })
  }


  createCountryForm(): FormGroup {
    return this.fb.group({
      id: new FormControl(null)
    })
  }

  createMajorForm(): FormGroup {
    return this.fb.group({
      department:new FormControl(null),
      subject: this.createSubjectForm()
    });
  }
  
  
    createSubjectForm(): FormGroup {
    return this.fb.group({
      id: new FormControl(null)
    })
  }

JSON to create a user on the server side:

 {
    "name": "Kevin",
    "details": [{
        "country": {
            "id": 1 //used in select box. It is not getting patched from user form.(problem area)
        },
        "major": [{
            "department": "Science",
            "subject": {
                "id": 2 //used in select box. It is not getting patched from user form. (problem area)
            }
        }]
    }]
  }

Definition of Class Country:

export class Country{
    id: number;
    name: string;
}

Data for countries:

 countries : Country [] = [
    {id:1, name:"Serbia"},
    {id:2, name:"Slovenia"},
    {id:3,name:"India"}
    ]

HTML part for selecting country:

<div [formGroupName]="country">
                            <select>
                              <option
                                *ngFor="let c of countries"
                                [Value]="c.id"
                              >
                                {{ c.name }}
                              </option>
                            </select>
                          </div>

Definition of Class Subject:

export class Subject{
  id:number;
  name:string;
}

Data for subjects:

   subjects : Subject [] = [
    {id:1, name:"Chemistry"},
    {id:2, name:"Physics"},
    {id:3, name:"Botany"}
    ]

HTML part for selecting subject:

  <div [formGroupName]="subject">
                                <select>
                                  <option
                                    *ngFor="let s of subjects"
                                    [Value]="s.id"
                                  >
                                    {{ s.name }}
                                  </option>
                                </select>
                              </div>

Explanation of Problem: The user details form contains nested form arrays and form groups. While populating the select boxes for both subject and country works, setting the 'id' value for both subject and country in the user form is not successful.

The current method used for patching the user form is:

this.service.registerUser(this.userForm.value);

What is the correct way to set the select box values? Is there any mistake in the TypeScript or HTML code? Do additional steps need to be taken to set the 'id' value from the select boxes for both subject and country in the user form? How to set controls inside the select boxes? Should the select box value be patched independently? The form will also be used for editing purposes, if that affects how values are set. Any suggestions or solutions would be greatly appreciated. Thank you in advance.

Answer №1

  1. Make sure to assign the formControlName attribute to your HTML controls in order to connect your template with the form model.
  2. Avoid using [] around formGroupName when binding to a string value instead of a variable.

Consider this structure:

<div formGroupName="city">
   <select formControlName=“name”>
   …

If you need to update the value, you can do so by using:

this.userForm.get(‘city.name’).patchValue(456);

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

Exploring Angular2: A Guide to Interpolating Expressions in Templates

Is it possible to interpolate different types of Javascript expressions? Along with displayed properties like object.property and short expressions such as {{1+1}}, what other valid Javascript expressions can be used for interpolation? ...

Differentiate between function and object types using an enum member

I'm currently experimenting with TypeScript to achieve narrowed types when dealing with index signatures and union types without explicitly discriminating them, such as using a switch case statement. The issue arises in the code snippet below when at ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Determine the variable height of a div containing dynamic content in order to execute a transform

Looking to create a dynamic container that expands when a button/link is clicked? The challenge lies in achieving this expansion effect with a smooth transition. By using the height: auto property, the container can expand to fit its content, but incorpora ...

Struggling with resolving Angular dependencies

Every time I try to run npm install or any other npm command, a string of dependency errors pops up, leaving me puzzled on how to resolve them. Here are the steps I've taken so far:--> Forced update of angular CLI. Reinstalled Node. I eve ...

The type 'Observable<unknown>' cannot be assigned to type 'Observable<Something>'

I am a beginner with Angular and Firebase, facing an issue while attempting to import of from rxjs and returning null using switchMap in my auth.service.ts. import { ActivatedRoute } from '@angular/router' import { Observable, of } from 'r ...

Struggling with setting up a reducer in TypeScript?

I am currently working through a Microsoft tutorial on using Redux with TypeScript. Although I have been following the steps outlined in the tutorial at https://github.com/Microsoft/TypeScript-React-Starter, I have encountered a problem in the final stage: ...

What is the process by which Angular2+ ngFor directive cycles through the ref iterable?

My curiosity led me to dive into the inner workings of the Angular *ngFor directive. I was particularly interested in understanding how Angular interprets the iterable object passed to the directive - whether it re-evaluates it at each loop iteration simil ...

Is it possible to customize the color of the placeholder and clear-icon in the ion-search bar without affecting

I am working with two ion-search bars and I need to customize the placeholder and clear icon color for just one of them. <ion-searchbar class="search-bar" placeholder="search"></ion-searchbar> My goal is to target a specific i ...

typescript what type of functionality do dynamic class methods provide

I'm currently working on building a class that creates dynamic methods during the constructor stage. While everything is functioning properly, I've encountered an issue with VS Code's auto suggestion not recognizing these dynamic methods. Ho ...

Tips for merging individual Koa-Routers using Typescript

My approach to organizing routers in my project involved categorizing them based on their purpose. Here's how they are structured: routers/homeRouter.ts import * as Router from 'koa-router'; const router: Router = new Router(); router ...

Leveraging an abstract class in Typescript for easy function sharing

When working with Typescript, I encountered a situation where I had 2 functions containing the same function code. To streamline my code, I decided to extract this common function into its own file. Currently, I have implemented it as shown below. However ...

Leveraging Firebase Functions version 2 with Angular via Angular Fire

Recently, I encountered a small issue. After migrating my Firebase Cloud Function (onCall) to v2, they recommended calling it via URL using httpsCallableFromURL from 'firebase/functions'. The challenge is that in our Angular project, we rely on h ...

Tips for maximizing efficiency when working with both a collection of items and additional elements inside and outside of the array

I am working with an array of items and need to dynamically add or remove extra items while dragging. The items are being accessed 60 times per second, and I'm curious about the performance impact of my current implementation. class Hello { get con ...

Is there a way to capture an unauthorized response and prompt the user to enter a password before attempting to retry it?

I am currently in the process of developing an application that features a backend with straightforward authentication and a GET request. One of the key functionalities I want to implement is displaying a dialog prompting the user to re-enter their passwor ...

having difficulties connecting the paginator with MatTable

I'm struggling to implement pagination for my mat-table in Angular 6. I've referenced some examples from the following link, but unfortunately, it's not functioning as expected: https://material.angular.io/components/table/examples While t ...

Angular: Trigger service worker to handle push notification event from service

Is it possible to call the service worker push event from a custom service in Angular? I implemented this code in my service, and it works on desktop and android, but not on iPhone. navigator.serviceWorker.register('sw.js'); Notification.request ...

Exploring the creation of an Angular service that utilizes HttpClient for making GET requests, with a focus on the different

I've been diving into Angular lately and I'm facing some challenges with handling get requests. If you're interested, you can check out my code on Angular Stackblitz import { HttpClient} from '@angular/common/http'; import { Inject ...

Establish a connection to Cosmos DB from local code by utilizing the DefaultAzureCredential method

I've created a Typescript script to retrieve items from a Cosmos DB container, utilizing the DefaultAzureCredential for authentication. However, I'm encountering a 403 error indicating insufficient permissions, which is puzzling since I am the ad ...

The operation of accessing a property of an undefined element fails due to unavailability, hence the error "Cannot

Hey everyone, I'm encountering an issue with opening a project developed in Angular 5.2.0 with Angular CLI version 1.7.4, while my Angular CLI version is 14.0.7... I ran "npm install" without any errors, but when I run "ng version" to check the local ...