Adding Angular FormArray FormControls using push method

I have a form where I need to input company names and save them in a list of strings in the database. However, I am facing an issue where the value of the company in the form array is always empty.

<button (click)="addNewCompany()">Add New Company</button><br><br>
<form [formGroup]="myForm">
    <div formArrayName="companies">
        <div *ngFor="let comp of getForm(); let i=index>
            <fieldset>
                <legend>
                    <h3>COMPANY {{i+1}}: </h3>
                </legend>
                <label>Company Name: </label>
                <input formControlName="comp" /><span><button (click)="deleteCompany(i)">Delete Company</button></span>
            </fieldset>
        </div>
    </div><br>
  </form>


export class AppComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      companies: this.fb.array([])
    });
  }

  getForm(): any {
    return this.myForm.get("companies")["controls"];
  }

  addNewCompany() {
    const control = <FormArray>this.myForm.get("companies");
    control.push(this.fb.control(''));
  }

  deleteCompany(index) {
    let control = <FormArray>this.myForm.controls.companies;
    control.removeAt(index);
  }

}

Check out the Stackblitz example here!

Answer №1

Your inclusion of the StackBlitz demo is really helpful!

<input [formControlName]="i" />

When working with a FormArray, remember that the items are indexed as 0, 1, 2.... These values should be used for the formControlName. Be sure to use the [] notation to correctly reference the property value of i, rather than just using it as a string.

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 equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

Issues with the linear-gradient feature in Ionic3 are preventing it from properly functioning

I'm currently experimenting with creating a unique gradient color in my Ionic3 variable.sass file. $colors: ( primary: #4471C1, secondary: #32db64, danger: #f53d3d, light: #f4f4f4, dark: #222, newcolor: linear-gradient( ...

An issue arises in Angular 17 where the view does not refresh when using setInterval, accompanied by the NG0500

I am currently working on a countdown timer feature where I want to continuously update the 'seconds' value in real-time, but I'm facing an issue with the UI not reflecting these updates. Whenever I attempt to implement this without utilizi ...

Tips for fixing prettier errors in express and TypeScript code

I have set up a simple Node/Express + Typescript application app.listen(PORT, (): void => { console.log(`app is running in ${environment} and listening on port ${PORT}!`); }); I am encountering an error and I am unsure of the cause? Replace PORT, wit ...

The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using ac ...

Angular enables the use of multiple instances of a service from the parent component to the child component

I recently came across this discussion: Utilizing multiple instances of the same service. Can one utilize multiple instances of a service from parent to children? For instance, imagine having an ElementService in the ParentComponent with 2 separate instan ...

Is it possible to incorporate mapped types while also including a particular property?

My initial idea was something along these lines: type Foo<T, K extends string> = K extends "isDirty" ? never : { [P in K]: T; isDirty: boolean; }; However, Typescript is still unaware that K will never be `"isDirty ...

Update the Azure AD token with a personalized JWT token

We have developed an Angular 11 frontend application with a .NET 5 backend API. Our system offers two login options: 1. Basic authentication using user details stored in our system with JWT token generation, and 2. Azure AD authentication. During the Azu ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

Creating a component in Angular that utilizes multiple nested FormGroups

When attempting to nest multiple FormGroups, everything works smoothly if the template is not extracted into separate components. For instance, the following example functions as expected: Template <form [formGroup]="baseForm"> <div formGr ...

No routes found to match. URL Segment: ''. This issue occurs when attempting to utilize child routes with Angular 2

I am having issues with this specific plunker that seems to not be working correctly. To try and fix the problem, I attempted to comment out a section of code... RouterModule.forRoot([ { path: "", component: TestComponent, ...

Using Angular's filter pipe to search within a nested array

We are attempting to implement an angular pipe for filtering a list of sub-items, with the goal of removing parent items if there are no child items present. Here is the HTML code snippet we are using: <div class="row border-bottom item" *n ...

In the case that the prop is empty or undefined, display an error message before rendering the full component

I am working on an ImageBlock component, which has several props like url, alt, caption, and optionally quality with a default value of 75. The essential prop here is the url. I need a quick way to immediately display an AlertError if the url is not provi ...

The application is having trouble accessing the property 'isXXXXX' because it is undefined

My attempt to utilize a shared service in one of my components has been successful when used with the app's root component. However, I encountered an error when trying to implement it on another module or dashboard. https://i.sstatic.net/x3rRv.png s ...

Redis is prepared and awaiting authorization for authentication. ReplyError: NOAUTH Authentication needed

When attempting to connect to a Redis instance hosted on redislab, an error message is received indicating Redis ready ReplyError: NOAUTH Authentication required. const pubClient = createClient({ url: `${config.redisLabHost}:${config.redisLabPort}` }); pub ...

Techniques for Grouping an Array of Objects by a Specific Value Key in Angular

I have the following array that needs to be grouped by section_name in HTML. Additionally, I need to first check if the length of the array values for section_name is greater than zero before displaying the results grouped by section_name. I hope my expl ...

What is the process for adding an item to the dictionary state?

I'm currently working on a function to push an object to the state in my code. The goal of this function is to duplicate the first state object and append it to the end of the state array. addField() { const index = (this.state?.fields.length) -1 ...

How to display an array with JSON objects in Angular 4

Looking to display specific data from an array in my .html file that originates from my .ts file: myArray: ["03/05/2018", "2:54", "xoxo", "briefing", "your", [{ "Id": "1", "Time": "20:54", "Topic": "mmmmm", "GUEST1": { "Role": "HS" ...

Can you merge two TypeScript objects with identical keys but different values?

These TypeScript objects have identical keys but different properties. My goal is to merge the properties from one object onto the other. interface Stat<T, V> { name: string; description: string; formatValue: (params: { value: V; item: T }) =&g ...

Encountered an error - 'SyntaxError: unexpected token: ':'' while attempting to load a JSON file for ngx-translate using the Karma test runner

I am currently in the process of setting up system tests for my Angular application. The app utilizes the TranslateModule (ngx-translate) in this manner: TranslateModule.forRoot({ defaultLanguage: 'de', loader: { provide: Tra ...