Extracting values from the form array and form group functions in Angular: A step-by-step guide

The code can be found at the link above.

    export class AppComponent  {

      title = 'Nested FormArray Example Add Form Fields Dynamically';

      empForm:FormGroup;


      constructor(private fb:FormBuilder) {

        this.empForm=this.fb.group({
          employees: this.fb.array([]) ,
        })
      }


      employees(): FormArray {
        return this.empForm.get("employees") as FormArray
      }


      newEmployee(): FormGroup {
        return this.fb.group({
          firstName: '',
          lastName: '',
          skills:this.fb.array([])
        })
      }


      addEmployee() {
        console.log("Adding a employee");
        this.employees().push(this.newEmployee());
      }


      removeEmployee(empIndex:number) {
        this.employees().removeAt(empIndex);
      }


      employeeSkills(empIndex:number) : FormArray {
        return this.employees().at(empIndex).get("skills") as FormArray
      }

      newSkill(): FormGroup {
        return this.fb.group({
          skill: '',
          exp: '',
        })
      }

      addEmployeeSkill(empIndex:number) {
        this.employeeSkills(empIndex).push(this.newSkill());
      }

      removeEmployeeSkill(empIndex:number,skillIndex:number) {
        this.employeeSkills(empIndex).removeAt(skillIndex);
      }

      onSubmit() {
        console.log(this.empForm.value);
      }


    }

This is the template:

    <form [formGroup]="empForm" (ngSubmit)="onSubmit()">

      <div formArrayName="employees">

        <div *ngFor="let employee of employees().controls; let empIndex=index">

          <div [formGroupName]="empIndex" style="border: 1px solid blue; padding: 10px; width: 600px; margin: 5px;">
            {{empIndex}}
            First Name :
            <input type="text" formControlName="firstName">
            Last Name:
            <input type="text" formControlName="lastName">

            <button (click)="removeEmployee(empIndex)">Remove</button>


            <div formArrayName="skills">

              <div *ngFor="let skill of employeeSkills(empIndex).controls; let 
 skillIndex=index">



                <div [formGroupName]="skillIndex">
                  {{skillIndex}}
                  Skill :
                  <input type="text" formControlName="skill">
                  Exp:
                  <input type="text" formControlName="exp">

                  <button (click)="removeEmployeeSkill(empIndex,skillIndex)">Remove</button>

                </div>

              </div>
              <button type="button" (click)="addEmployeeSkill(empIndex)">Add Skill</button>
            </div>


          </div>

        </div>
      </div>

      <p>
        <button type="submit">Submit</button>
      </p>

    </form>


    <p>
      <button type="button" (click)="addEmployee()">Add Employee</button>
    </p>

Therefore, in order to retrieve values of firstName, lastName from empForm and skill: '',exp: ''from, skills array...

this function is currently not working for me to get values..

      get from_date() {
        return this.empForm.get("from_date");
      }

....this is not working.. I am also unable to extract values from the skills array. Please assist.

Answer №1

Upon form submission, the structure of this.empForm.value can be outlined using the following interfaces.

export interface Employee {
  firstName: string;
  lastName: string;
  skills: Skill[];
}

export interface Skill {
  exp: string;
  skill: string;
}

The format of empForm.value is as follows:

{
  employees: Employee[];
}

When querying empForm during submission, data retrieval mimics regular object queries.

onSubmit() {
  const firstNames = this.empForm.value.employees.map(x => x.firstName);
  const firstEmployeeSkills = this.empForm.employees[0].skills.map(x => x.skill);
  // etc
}

Regarding this.empForm.get("from_date"), there is no "from_date" property in empForm, thus it will not return any value.

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

Found in the NgModule.imports section of the AppModule, yet was unable to be identified as an NgModule class in Angular version 12.2.9

Just set up a fresh angular 12 application and installed version 12 of @angular/material. Now I'm trying to implement it by adding this basic element: <mat-drawer-container></mat-drawer-container> However, all I see in the browser is a wh ...

Transfer data from one array to another within a React application

I am dealing with this state structure: this.state = { data: { tags: [] }, items: [], input: '' }; My goal is to populate the tags array with the same values as the items array when submitting the data. var newData = t ...

Leveraging external files with Django template referencing

Having trouble including external JavaScript and CSS files in the head tags of my Django template. They only seem to work when placed before the closing body tag. Any idea why this is happening? Another issue I'm facing is that when using inheritance, ...

VueJS 3 - Issue with applying the <router-link-active> class to routes that share the same path starting name

In my navigation bar, I have created 3 links which are all declared at the root level of the router object. I've applied some simple styling to highlight the active link on the navbar using the <router-link-active> class. Everything works as exp ...

Invalid Syntax: The token '21' is found unexpectedly at column 12 in the expression [2013-08-28 21:10:14] beginning at [21:10:14]

I'm in the process of creating a straightforward directive for a date countdown. However, I've hit a roadblock with this particular error: Syntax Error: Token '21' is an unexpected token at column 12 of the expression [2013-08-28 21:10 ...

The checkbox fails to display as selected in the user interface despite setting the checked property to true in JavaScript

In the table generated dynamically using an ng-repeat, I have checkboxes. The checkboxes are created as shown below: <input type="checkbox" id="chkView{{::myObj.TeamId}}" ng-disabled="disableView(myObj)" ng-click="setViewSelectio ...

What is the process for exporting data from MongoDB?

Recently, I created a web application for fun using Handlebars, Express, and Mongoose/MongoDB. This app allows users to sign up, post advertisements for others to view and respond to. All the ads are displayed on the index page, making it a shared experie ...

What is the best way to fill HTML tables using an ajax response?

This is a Laravel blade view/page that requires updating without the need to refresh the entire page. The blade.php code functions correctly and retrieves data from a MySQL database, but there seems to be an issue with the AJAX and JavaScript implementati ...

Clicking on a search result does not trigger the popup to open in the App.vue file

Whenever I click on a search item, my goal is to open the Popup. Why does this.$emit('openPopup', bookId); not work in the selectBook(bookId) method? In Results.vue component, the search results are displayed using Google Books API: <template ...

The object function router(req, res, next) is encountering an error as it does not contain the required method for handling the request

I am trying to add a new row to my MySQL database, but I encountered an error message. Here is the scenario: I have set up Passport and hjs in my project. I am passing form data from app.js to a JavaScript file where I aim to insert the data. Object funct ...

"Utilizing ngrx Effects: Triggering a null Action

Can anyone guide me on how to make my ngrx/store effect dispatch an empty action? I'm currently working with Angular 6 and rxjs 6: @Effect() testEffect$ = this.actions$.ofType(FIRST_ACTION).pipe( map((x) => { if (x === y) { ...

Vue's v-on:click feature stops functioning correctly post-build

I have successfully integrated the Vue slide example from this link into my Angular template. Everything works fine when running ng serve, but after building with ng build and then trying to start it again with ng serve or from the dist folder using npm s ...

Unusual Glitch in Bootstrap 3 Dropdown Menu

I am currently developing a website using Bootstrap 3. I am encountering an issue with the navbar dropdown. When I click on the link, it changes to show "expand child menu" and "collapse child menu". To clarify, here is the image I am referring to: Initi ...

What steps should I take to modify the API addresses within the React project build?

In my React project, I am looking for a method to dynamically change the API addresses after building it. Is there a way to accomplish this without using environment variables? I want to be able to modify the API address even after the build process is c ...

I am experiencing difficulties in assigning values to a formArray

I am struggling to update values in an array form, as I am facing challenges setting new values. Although I attempted to set values using patch value, my attempts were unsuccessful. // Component.ts this.packageForm = this.formBuilder.group({ title: [&a ...

I am hoping this script will activate a JavaScript function rather than simply greeting

I stumbled upon a working script, but I must stress that my knowledge of JQuery is quite limited. Here's the script in question: document.getElementById("id_of_button").onclick = function() {clickFunction()}; function clickFunction() {alert("hello") ...

Updating the status of a checkbox array within the reducer to reflect changes made in the user interface

I've implemented something similar in React: const CheckboxItems = (t) => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', labelText: t('cancellations.checkBoxItemsCancelled&apos ...

Exploring the power of promises in the JavaScript event loop

Just when I thought I had a solid understanding of how the event loop operates in JavaScript, I encountered a perplexing issue. If this is not new to you, I would greatly appreciate an explanation. Here's an example of the code that has left me scratc ...

Error: The functionality of Object(...) in reactjs is not recognized

After attempting to streamline this react component by moving fillCalendar() out of the component as a method and into its own JS file, I encountered an issue. The original setup involved setting this.state.datesArray in a componentWillMount() lifecycle me ...

Using the drop and drag features within a table cell

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.8.2.js"></script> <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script> & ...