Oops! There seems to be a hiccup: Unable to locate the control with the specified path: 'emails -> 0 -> email'

I am attempting to design a form incorporating a structure like this:

formGroup

formControl

formControl

formArray

formGroup

formControl

formControl

However, upon clicking the button to add reactive fields and submitting the form after filling it out, the first field does not retain any data. The following errors are being displayed:

ERROR Error: Cannot find control with path: 'emails -> 0 -> email'

and

ERROR Error: Cannot find control with path: 'emails -> 0 -> send'

In my app.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent{


  profileForm = this.fb.group({
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
    }),
    emails: this.fb.array([''])
  });


  get emails() {
    return this.profileForm.get('emails') as FormArray;
  }

  addEmail() {
    this.emails.push(this.fb.group({
      email:[''],
      send:['']
    }));
  }

  constructor(private fb: FormBuilder){}

  public submit():void{
    console.log(this.profileForm.value);
  }


}

In my app.component.html file:

<form [formGroup]="profileForm" (ngSubmit)="submit()">

  <div>
    <label>firstName</label>
    <input type="text" formControlName="firstName">
  </div>

  <div>
    <label>lastName</label>
    <input formControlName="lastName" type="text">
  </div>

  <div formGroupName="address">
    <label>Adresse</label>
    <label>street</label><input formControlName="street" type="text">
    <label>city</label><input formControlName="city" type="text">
    <label>state</label><input formControlName="state" type="text">
  </div>

  <div formArrayName="emails">
    <h2>Aliases</h2>
    <button type="button" (click)="addEmail()">+ Add another alias</button>

    <div [formGroupName]="i" *ngFor="let e of emails.controls; let i=index;">
      <div>
        <label>email:</label>
        <input type="text" formControlName="email">
        <input type="checkbox" formControlName="send">

      </div>


    </div>
  </div>

  <button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>

Answer №1

Utilize

Emails: this.fb.array([])

in place of

Emails: this.fb.array([''])

See a Sample Demo on StackBlitz


Check out these resources for more information:

Learn about Creating an in-place editable table using FormArray

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

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

React TypeScript throws an error when a Socket.IO object is passed to a child component and appears as undefined

Currently, I'm developing a simple chat application as part of my university course. The code below represents a work-in-progress page for this project. While I am able to get the socket from the server and use it in the main component without any is ...

Exploring the world of nested observables in Angular through cascading HTTP requests

My plan involves the following steps: Make a request to https://reqres.in/api/users/2 This request will return the following response. { "data": { "id": 2, "first_name": "Janet", "last_name": "Weaver", "avatar": "https://s3.ama ...

Creating a unique type with a suffix of `px`

Understanding how to create a Position type class is clear: class Position { x: number = 0; y: number = 0; } However, I now require the x and y values to be integers with the suffix of px, like this: const position = { x: '1px', y: &ap ...

Sorting character values in TypeScript using ascending and descending order in a JSON array

In my dataset of homes, I have the following information: var homes = [ { "h_id": "3","city": "Dallas","state": "YYYY","zip": "75201","price": "162500" }, { "h_id": "4","city": "CA","state": "ZZZZ","zip": "90210","price": "319250" }, { "h ...

"Unable to convert object into a primitive value" error message appears on Internet Explorer

Currently working on a webpage using Angular 7. The code is functioning perfectly in Chrome, however, I am facing an Exception error while running it in IE: An issue arises: Can't convert object to primitive value (polyfills.ts) The source of the er ...

Delay in input bar after extensive user engagement

I've been grappling with a perplexing issue for quite some time now, and it's proving to be quite elusive. In my Angular webshop, the product overview page features a product component with a lazily loaded, highly compressed image, a title, quan ...

What is the best way to access dynamic URL parameters in the Next.js 13 app router from a nested server-side component?

This query pertains to the Server-Side components in Next.js 13 app router: I have a good grasp on how the slug parameter is passed to the default function in app/blog/[slug]/page.tsx: export default function Page({ params }: { params: { slug: string } }) ...

What could be causing the scaling issue in my ng2-chart data?

I am currently receiving data from a service that is being displayed in an ng2-chart. The chart is currently showing dummy data until the actual data is available. Below is the HTML code: <canvas baseChart [datasets ...

Is it possible for Typescript to resolve a json file?

Is it possible to import a JSON file without specifying the extension in typescript? For instance, if I have a file named file.json, and this is my TypeScript code: import jsonData from './file'. However, I am encountering an error: [ts] Cannot ...

Connecting conversations in react

When working with jQuery, I often utilize the modal dialog chaining technique. For example: $.Deferred().resolve().promise() .then(function () { return runDialog1(someProps); // return promise }) .then(function (runDialog1Result) ...

Tips and tricks for effectively implementing clientX in Angular 2

I attempted to utilize the Observable feature to track the clientX property of an element. Here's what I tried: `const wrap = document.getElementById('wrap'); const body = document.body; const mouseDown = Observable.fromEvent(wrap, &apos ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

Upgrade from AngularJS to the latest version of Angular, version 8

I'm trying to convert this AngularJS code into Angular 2+, but I'm having some trouble. Any ideas on how to do it? I've searched around, but this specific line is confusing me. scope.variable.value = event.color.toHex() Old Code: functi ...

Error: Value of incoming scope in Angular Directive is not defined

When working in html, I passed an object into a directive like this: <lcd-code ldcCode="{{ detail.program.ldcCode }}"></lcd-code> The value of detail.program.ldcCode is "PSIH"... However, in the Directive, it is showing up as undefined: var ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

Bringing in TypeScript definitions for gridster

After starting a new ionic project, I decided to include the gridster.js library by running npm install gridster and npm install @types/jquery.gridster in the root directory of my project. However, when trying to import the installed definitions, I encount ...

What steps need to be taken in VSCode to import React using IntelliSense?

When I press Enter in that image, nothing seems to occur. I believed IntelliSense would automatically insert import React from 'react'; at the beginning of the file. https://i.stack.imgur.com/7HxAf.png ...