Facing issues with updating a dynamic input form array in Angular

For my Angular-12 project, I am currently working on implementing a dynamic input fields FormArray within a Reactive Form to handle updates. Below is the code snippet:

Interface:

export interface IResponse<T> {
  message: string;
  error: boolean;
  code: number;
  results: T;
}

export interface IEmployees {
  employees: IEmployee[];
}

export class EmployeeResponse {
  results!: { employee: IEmployee; };
}

export interface IEmployee {
  id?: number;
  current_residential_address?: string;
  employeephones?: IContact[];
}

export interface IContact {
  id?: number;
  phone_number: string;
  phone_type_id?: number;
  phonetypes?: {id:number,type_name:string};
  is_primary_contact_number?: boolean;
}

Service:

getContactById(id: number): Observable<EmployeeResponse> {
  return this.http.get<EmployeeResponse>(this.api.baseURL + 'company/employees/fetchbyid/' + id, this.httpOptions);
}

public updateContact(id: number, employee: IEmployee): Observable<any> {
  return this.http.post(this.api.baseURL + 'employees/contact/update/' + id, employee, this.httpOptions);
}

Component:

(component code here...)

I have encountered an issue where only the single data field (current_residential_address) gets updated upon submission, while the array (contacts) does not reflect the changes. How can I resolve this issue?

Any help would be appreciated.

Answer №1

Within your FormGroup, there is a discrepancy where the expected employeephones FormArray is actually named contacts FormArray.

updateContact() {
  this.contactInfoForm = this.fb.group({
    id: [''],
    current_residential_address: ['', [Validators.required]],
    contacts: this.fb.array([this.addContactFormGroup()]),
  });
}
mapFormValueForContactModel() {
  this.contactdata.current_residential_address = this.contactInfoForm.value.current_residential_address;
  this.contactdata.employeephones = this contactInfoForm.value.contacts;
}

Solution

Adjust

this.contactInfoForm.value.employeephones
to instead reference
this.contactInfoForm.value.contacts
.

Additionally, ensure that mapping

this.contactInfoForm.value.contacts
correctly returns the desired output, specifically with phone_number being extracted from each phone number object within the FormGroup (which contains various phone types) due to interaction with ngx-intl-tel-input.

mapFormValueForContactModel() {
  this.contactdata.current_residential_address =
      this.contactInfoForm.value.current_residential_address;
  this.contactdata.employeephones =
  this.contactInfoForm.value.contacts.map(
      (value) => {
        return {
          phone_type_id: value.phone_type_id,
          is_primary_contact_number: value.is_primary_contact_number,
          phone_number: value.phone_number.e164Number
        };
      }
    );
}

See Example Solution on StackBlitz

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

Angular and Bootstrap do not support margin styles

While working with Angular 5 and Bootstrap, I have encountered an issue with using inline styles for margin. The template I am using is as follows: @Component({ selector: "dynamic-container-component", template: ` <div styl ...

Tips for displaying a specific JSON element when using interpolation in Angular

How can I display a specific element from a JSON object using Angular interpolation? public responseData:any; renderTokenCard(){ this.mundipaggS.checkToken().subscribe((response:any)=> { console.log("success: ", JSON.stringify(res ...

Having trouble with Tailwind's 'select-none' class not functioning properly in mobile Safari

While working on my NextJS app, I encountered this code block: <div className="select-none"> bro </div> Surprisingly, even with the "select-none" class added, I can still select it in mobile Safari. I tried adding the ...

Utilizing Angular 2's ViewChild within the <router-outlet> Tag

I've been working on a project using Angular 2. Within the MainComponent, I'm utilizing @ViewChild to reference child components. The MainComponent also contains a <router-outlet> where various components are loaded. My query is, how can I ...

How to Set Up TypeScript in Laravel 5.6

I've been encountering errors while trying to set up TypeScript in Laravel 5.6 and running 'npm run dev'. Below is my configuration - can someone help me identify what's wrong? webpack.mix.js let mix = require('laravel-mix' ...

Is there a way to seamlessly share TypeScript types between my Node.js/Express server and Vite-React frontend during deployment?

I'm currently tackling a project that involves a Node.js/Express backend and a Vite-React frontend. My goal is to efficiently share TypeScript types between the two. How should I configure my project and build process to achieve this seamless type sha ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

Error: Can't find module ng-uikit-pro-standard

I am currently working on implementing datatables in Angular with material design. To achieve this, I am referencing a tutorial from this source. The tutorial instructs to import the MdbTableDirective, MdbTablePaginationComponent, and MdbTableService from ...

When using Angular 2, an error may occur where you receive a message stating that you cannot read the property 'length' of undefined while attempting to call

When creating a component (let's call it A) with the @input decorator to retrieve values from the selector, keep in mind that this component will generate text fields based on the input values specified in the selector. Component A is then utilized in ...

Angular date function - I aim to increase the date by 7 days and showcase it in an HTML format

Received a date from an API in the format: 31-08-2021 13:58. I need to display this date in one mat-cell and then in another cell, adding 7 days to it. For example: 7-09-2021 13:58. How can I achieve this? ...

Cease the repetitive running of the function in a gentle manner

When working with typescript/nodejs, how can one gracefully shutdown a component that is continuously performing tasks? For instance, I would like to allow the user to send a SIGINT signal, such as by pressing <ctrl+c>, in order to halt the program g ...

"Error encountered: 'Callable function cannot be invoked on Mongoose model

In my Nest JS service, the code structure is as follows: import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { Collection } from './inter ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

What is the best way to retrieve the index of the chosen option from a select element in Angular when

My Angular application includes a simple <select> element using Material design: <mat-form-field> <mat-label>Type</mat-label> <mat-select placeholder="Type" formControlName="type" name="type" id="name"> <mat-option ...

Middleware comes back in session

I have a class that contains a middleware function which I need to utilize. However, when I try to use the this statement within the middleware, it returns undefined. Here is the structure of the class: export class Validator { constructor(options: va ...

The intricacies of Mongoose schemas and virtual fields

I'm currently working on a NodeJS project using TypeScript along with Mongoose. However, I encountered an issue when trying to add a virtual field to my schema as per the recommendations in Mongoose's documentation. The error message stated that ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Instead of relying on Vue TypeScript, we are leveraging IntelliJ with TypeScript 5.0.3 to compile our Vue project

My current version of IntelliJ IDEA is 2023.1 (Ultimate Edition) Build #IU-231.8109.175, released on March 28, 2023. I am facing an issue where my project fails to compile using "Vue TypeScript", resulting in some type mismatches being overlooked. In the ...

Angular Material: Highlighted row moves to the top of the table

Utilizing Angular and Material, a straightforward table has been developed to showcase data in a list format. The table can be accessed on Stackblitz via this link: angular-mat-table-selected-cell The objective is to highlight a selected row, causing it ...

How to display the menutoggle button in a child page using Ionic 2

Is there a way to display the 'menu toggle' button on subpages of the side menu application? Currently, only the root page has the menu toggle button while the child pages have the back button. ...