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

Issue with dependency injection in Angular 16 when used as a standalone feature

Here are my standalone API calls within the service: import { Injectable} from '@angular/core'; import { ProductEndPoints } from '../../constants/apiConstants/product-endpoints'; import { HttpClient} from '@angular/common/http&ap ...

Angular 11 - Error: The 'fetch' method could not be executed on the 'Window' object due to an illegal invocation

I have encountered an issue with a dependency in my current project. This particular dependency relies on isomorphic-unfetch for its functionality. Strangely, I am able to run isomorphic-unfetch without any problems within Angular 11. However, when I inclu ...

Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface. const fields = [ { id: 'textInput_1', fieldType: 'text', }, { id: 'selectInput_1', fieldType: 'sel ...

Calculating the Sum of Values in PHP using an HTML Form and Jquery

Looking to expand my knowledge of jQuery, I am attempting to create a straightforward page for practice. The goal is to develop a form that will send its values to PHP to be summed and return the results. These results will then be displayed dynamically on ...

How to automatically select an option in a dropdown based on a condition in Angular 2

Currently, I am constructing a select element within a form using an array of objects. My goal is to have one of the options automatically selected based on a specific attribute of the object (myobject.is_default). The initial template code appears as fol ...

Looking for guidance on integrating REST API consumption features into Ionic Framework 3.x?

It's been a long time since I last used the ionic framework. The version I worked with was 1, where every page created with Ionic Creator had its own controller for adding JavaScript code to consume my REST framework. Now that I've downloaded th ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

What is the best way to consistently position a particular row at the bottom of the table in AG-grid?

I have successfully implemented a table using AG-grid. Here is the code snippet: .HTML <ag-grid-angular #agGrid style="width: 100%; height: 100%; font-size: 12px;" class="ag-theme-alpine" [rowData]=&quo ...

Distributing elements evenly across the parent width using Angular FlexLayout for a responsive design

I need to create 3 div squares: div-left, div-middle, and div-right, each with a width of 300px. These squares should be arranged horizontally within the parent div main-section, which will adjust its size based on the screen width, being 1300px if the scr ...

What is the proper way to specify the type for the `clean-element` higher-order-component in React?

Error message: 'typeof TextareaAutosize' argument cannot be assigned to a type 'Component<{}, {}, any>'. Error: Property 'setState' is not found in 'typeof TextareaAutosize'. Here is the code snippet causin ...

The potential for an 'undefined' object in TypeScript React is a concern that should be addressed

Currently, I am honing my skills in using TypeScript with React and retrieving data from an API that I set up a few days back. The API is functioning properly as I am able to fetch data for my front-end without any issues. However, when I attempt to util ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

Enhance your WordPress website with Elementor and choose between React or Angular

I tried searching on Google, but I couldn't find any answers... Is it possible to create a custom Elementor widget in Wordpress using React or Angular? I want to build a component that will pull data from an API and dynamically render the page. I&apo ...

When posting on social platforms, the URL fails to display any metadata

We recently completed a project (Web Application) using React .net core with client-side rendering in React. One challenge we encountered was that when the app loads in the browser, it only displays the static HTML initially without the dynamic meta tags. ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

Leveraging the outcome of an Observable in one method with another Observable in Angular2

The issue at hand I am facing difficulty in utilizing the value returned by the Observable from getUserHeaders() within my http.get request. Error encountered Type 'Observable<void>' is not assignable to type 'Observable<Particip ...

Why won't angular ng update work? Is there a timeout issue with the proxy settings?

I am encountering a problem with my angular project. When I am at work, I use a proxy, but when I am at home, I do not. So I added the following: npm config set https-proxy http://xx.xx.xx.xx:9090 npm config set proxy http://xx.xx.xx.xx:9090 and it works ...

Is there a method to automatically create .stories.ts files in Angular Storybook?

I am seeking a way to automatically create a .stories.ts file within a component folder after executing the command ng g component my-component. The desired outcome should resemble this structure: my-component -my-component.component.html . ...

Achieve triple condition handling using *ngIf else technique

My goal is to suggest nearby establishments to the user based on their location. I need to handle two scenarios: The user has allowed access to their geolocation The user has not granted access to their geolocation While checking if the geolocation ser ...

Button located beneath or above each individual image within the *ngFor loop

With the *ngFor loop, I am able to populate images but now I want to include a button below or on each image. Unfortunately, my CSS knowledge is limited. Below is the code I have: HTML Code <div class="container"> <div ...