Is it possible for FormArray to return null?

Hello there. I've attempted various methods, but none of them seem to be effective. Currently, I am working on this task where I need to start a formArray for emails.

email: [testestest]

However, what I have is:

email: [testestest]

I'm encountering an issue with my email not registering the click. Please review my typescript file.

Below is the HTML code snippet:

Answer №1

Hey there, Alex! Looks like you have a Form Array of FormControls instead of a Form Array of formGroups. To reflect this in your .html file...

<form *ngIf="addForm" [formGroup]="addForm">
    <div class="form-control-row" formArrayName="email"
        *ngFor="let item of addForm.get('email').controls; let i = index;">
        <div class="input-box">
            <input type="text" placeholder="E - mail" [formControlName]="i">
            <img src="../../assets/Delete.svg" alt="x-icon">
      </div>
        </div>
</form>

Notice that you should use [formControlName]="i" instead of [fomGroupName]="i". Another way to approach this is by using...

<form *ngIf="addForm" [formGroup]="addForm">
    <div class="form-control-row" formArrayName="email"
        *ngFor="let item of addForm.get('email').controls; let i = index;">
        <div class="input-box">
            <input type="text" placeholder="E - mail" [formControl]="item">
            <img src="../../assets/Delete.svg" alt="x-icon">
      </div>
        </div>
</form>

In this case, we utilize [formControl]="item" within the loop. How did you create the formArray?

If you have an array of emails, you can do something like this:

email:  this.formBuilder.array(
             this.email.map(x=>this.formBuilder.control(x))
          )

This creates an array of FormControls using map function. Remember, in production, you need a getter for the array...

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

And then iterate over it using...

*ngFor="let item of emails.controls; let i = index;">

The usage of [formGroupName]="i" and formControl typically applies to a FormArray of FormGroups. For example...

email:  this.formBuilder.array(
             this.email.map(x=>this.formBuilder.group({email:x}))
          )

By transforming each element into a FormGroup with a FormControl "email". Check out this example on StackBlitz for a better understanding.

To add an element to the formArray, you can create a function like so:

  addEmail(email:any)
  {
    const array=this.addForm.get('email') as FormArray 
    array.push(this.formBuilder.control(email)) 

    const array2=this.addForm.get('email2') as FormArray
    array2.push(this.formBuilder.group({email:email})) 
  }

Note: To initialize an empty formArray initially, you should use...

    email:  this.formBuilder.array([])

When removing an element from the array, remember to pass the proper index to the delete function like so:

delete(index:number)
{
    const array=this.addForm.get('email') as FormArray
    array.removeAt(index)

}

Update your .html code accordingly with a click event for deletion:

  <div class="input-box">
        <input type="text" placeholder="E - mail" [formControl]="item">
        <img src="../../assets/Delete.svg" alt="x-icon" (click)="delete(i)">
  </div>

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

What is the most efficient method of organizing form components together?

After exploring numerous tutorials, I have yet to discover the ideal solution for properly marking up a form that contains logical groupings of elements such as labels, controls (input or select), and previous values - essentially single fields. My prefer ...

Enhancing the NextPage Typescript Type: A Step-by-Step Guide

I'm working on a NextJS dashboard with role-based access control and I need to pass an auth object to each page from the default export. Here's an image showing an example of code for the Student Dashboard Home Page: Code Example of Student Dashb ...

Updating the Angular2 function in the main app component causes the current component to be reset

I developed an application that has the following structure: app.component.ts import { Component } from 'angular2/core'; import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; import { NgClass } from &apos ...

Using the hook to implement the useContext function in React

I came across this definition export interface user{ email:string name:string last_name:string } export type UserType= { user: user; setUser:(user:user) => void; } const [user,setUser] = useState <user> ({ email ...

How to invoke a method in a nested Angular 2 component

Previous solutions to my issue are outdated. I have a header component import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Observable } from 'rxjs/Observable'; ...

Tips for packaging a Node TypeScript/JavaScript library using Webpack

I am currently working on a Node project with the following setup: Written in Typescript Using Webpack and ts-loader for bundling Targeting Node.js +-proj/ +-src/ |-file1.ts |-file2.ts |-file3.ts |-... |-package.json |-webpack.confi ...

The parameter type ‘DocumentData’ cannot be assigned to type ‘never’ in this argument

I've been struggling to find a solution to my issue: Ts gives me an error: Argument of type 'DocumentData' is not assignable to parameter of type 'never' I attempted the solution I found on this page: Argument of type 'Docume ...

Implementing service injection within filters in NestJS

Looking to integrate nestjs-config into the custom exception handler below: import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common'; import { HttpException } from '@nestjs/common'; import { InjectConfig } fro ...

determining the data type based on the function parameter even when a specific type parameter is provided

Consider this example: type UpdateFieldValue<T extends Record<string, unknown>> = (key: keyof T, value: SomeType) => void The goal is to have SomeType represent the value type of the property (key) within object T, with key being provided t ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

Incorrect deduction of the argument type for a higher-order function

If I wanted to create a function that takes an object of type T and another value, where the type P should somehow be restricted by T (for example, P should be an array of keys of T), I could easily write it like this: function customFunction<T, P exte ...

Ways to retrieve the most recent update of a specialized typing software

When attempting to run typings install in a sample project with the below typings.js file, I received a warning. How can we determine the latest version number and what does the number after the + symbol signify? { "globalDependencies": { "core-js ...

Deciphering the TypeScript type in question - tips and tricks

One of my abstract classes includes a static property with various properties, where default is consistently named while the others may have random names. public static data = { default: { //only this one always have 'dafault' name na ...

"Connecting multiple URLs to the same router link: A step-by-step guide

I am currently working on a small test project in Angular and I aim to incorporate a side navigation using Angular router outlet. My goal is to have two links: <a class="nav-link text-white" [routerLink]='["/link/to/one"]' routerLinkActive="a ...

Deciphering embedded struct data in GoLang

A specific struct in my code contains an array of another struct, for example: type Struct1 struct { Value string Items []Struct2 } type Struct2 struct { Value string } While using gorilla schema to decode Form values into S ...

Which one should I prioritize learning first - AngularJS or Laravel?

As a novice web developer, I am embarking on my first journey into the world of frameworks. After much consideration, I have narrowed it down to two options: AngularJS and Laravel. Can you offer any advice on which one would be best for me to start with? ...

Steps for launching Angular 5 application using Node.js server

I have developed an Angular 5 application that retrieves data from a node.js server. I successfully deployed the application to my web server hosted by FastComet, which supports node.js, but unfortunately, the server does not seem to be functioning properl ...

Troubleshooting Issue with Filtering Nested Object Array Based on Property

At the core of my data structure lies an array of orders, each containing an array of line items. These line items, in turn, are associated with their respective categories. I am currently attempting to filter the order array based on the category ID of th ...

Can Angular Universal help pinpoint the location of a window reference error?

My Angular Universal project was running smoothly until I added a significant amount of code and included some external npm libraries like Quill. Now, I am encountering a Reference error related to the window object. It seems that every time I reference wi ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...