Unable to allocate FormArray

Just delved into learning Angular and encountered a snag. I am trying to add and remove textfields for a form, so I attempted the following code in my component.ts file:

import {FormBuilder, FormGroup, FormArray } from '@angular/forms';

This is how the import statement looks like and then

  nameForm: FormGroup;
  formBuilder: FormBuilder;
  items: any[] = [];

  createItem(): FormGroup {
    return this.formBuilder.group({
      name: '',
      manufacture_date: ''
    });
  }
  ngOnInit() {
    this.nameForm = this.formBuilder.group({
      Name: ''
      items: this.formBuilder.array([ this.createItem() ])
    });
  }

  addItem(): void {
    this.items = this.nameForm.get('items') as FormArray;
    this.items.push(this.createItem());
  }

Here is the corresponding HTML

<div formArrayName="items"
     *ngFor="let item of nameForm.get('items').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="name" placeholder="Item name">
    <input formControlName="price" placeholder="Item manufacture date">
  </div>

  Chosen name: {{ nameForm.controls.items.controls[i].controls.name.value }}
</div>

The issue arises when working with items. Especially at

addItem():

I am receiving an error stating that this is an unused method, and for

this.items = this.nameForm.get('items') as FormArray;

I encounter Type FormArray is not assignable to type any[]. Property "includes" is missing in type FormArray

Additionally, when dealing with the HTML form, I face an error indicating Identifier 'controls' is not defined

There might be an alternative approach to achieve what I intend, but currently, I am unable to figure it out.

Answer №1

It is recommended to modify the type of items to FormArray: items: FormArray ;

and within ngOnInit():

{
    this.nameForm = this.formBuilder.group({
      Name: ''
      items: this.formBuilder.array([ this.createItem() ])
    });
this.addItem()
  }

update: there were some errors in the code that have been fixed and updated:

nameForm: FormGroup;
items: FormArray;
constructor(public formBuilder: FormBuilder){}

ngOnInit() {
    this.items = new FormArray([new FormControl('name'), new FormControl('manufacture_date')]);
    this.nameForm = new FormGroup({
        items: this.items
    });

    this.addItem();
    console.log(this.nameForm)
    console.log(this.items.controls);
}

addItem(): void {
    this.items = this.nameForm.get('items') as FormArray;
    this.items.push(new FormControl('name'));
    this.items.push(new FormControl('manufacture_date'));
}

html:

<div [formGroup]="nameForm">
    <div formArrayName="items">
        <div *ngFor="let item of items.controls; index as i">
            <input [formControlName]="i">
            {{item.value}}
        </div>
    </div>
</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

Error: The function $compile does not exist

Currently, I am working on developing an AngularJS directive using TypeScript. While testing my code in the browser, I encountered the following error: TypeError: $compile is not a function at compileComponent.js:14 Interestingly, the TypeScript compiler ...

Unable to set a breakpoint within Angular constructor or OnInit method

I am currently facing an issue with my Angular application where breakpoints set in F12 tools in Chrome or IE are not working. I have a simple test case below: export class LoginComponent implements OnInit { message: string; constructor(private r ...

Implementing a Map in Typescript that includes a generic type in the value

Here is a code snippet I am working with: class A<T> { constructor(public value: T) {} } const map = new Map(); map.set('a', new A('a')); map.set('b', new A(1)); const a = map.get('a'); const b = map.get(& ...

AngularJS UI-Router in hybrid mode fails to recognize routes upon initial page load or reload

It appears that when using the @ui-router/angular-hybrid, routes registered within an ng2+ module are not being recognized during the initial load or reload. However, these same routes work fine when accessed by directly typing the URL. I have followed th ...

Encountering difficulties in generating a personalized Angular Element

Currently, I am in the process of developing a custom Component that needs to be registered to a module. Here is how it is being done: app.module.ts import { createCustomElement } from "@angular/elements"; @NgModule({ declarations: [ExtensionCompone ...

I cannot access the 'isLoading' state in React Query because it is undefined

Since updating to the latest version of react query, I've been encountering an issue where the 'isLoading' state is returning undefined when using useMutation. Here's the code snippet in question: const useAddUserNote = (owner: string) ...

Encountering crashes while initializing the router in the constructor of a service in Angular 4.3

I've been scratching my head over this problem. It seems like I'm overlooking something simple. Let me show you what's inside my home.component.ts file: import { Component, OnInit } from '@angular/core'; import { AuthService } f ...

Leverage tsconfig.json within the subfolders located in the app directory during Angular build or ng-build process

In our Angular project, I am attempting to implement multiple tsconfig.json files to enable strictNullChecks in specific folders until all errors are resolved and we can turn it on globally. I have been able to achieve this functionality by using "referen ...

Develop an rxjs pipeline that merges values according to their type prior to executing them in an async manner using concatMap

In my code, there's an eventStream that deals with different types of events and sends them to the server via HTTP. import { from, Observable } from 'rxjs'; import { concatMap } from 'rxjs/operators'; type Update = number[]; inte ...

What is the best way to obtain a distinct collection from two arrays that eliminates the second appearance of an element based on a key's value, rather than the first as in the Lodash uniqueBy function?

Let's say I have two arrays... const arr1 = [ { id: 1: newBid: true } ]; const arr2 = [ { id: 1, newBid: false }, { id: 2, newBid: false } ]; My goal is to end up with an array that looks like this [ { id: 1, newBid: false }, { id: 2, newBid: fals ...

Using [file_id] as a dynamic parameter in nextjs pages

I am working with a nextjs-ts code in the pages/[file_id].tsx file. import Head from 'next/head'; import Script from 'next/script'; import Image from 'next/image'; import Link from 'next/link'; import { NextApiReques ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

``Should one prioritize the use of Generics over Inheritance, or is there a better way

We are currently in the process of implementing new contracts for our icons system, and we have encountered a debate on which approach is more preferable. Both options result in the same interface: Using Generics -> Although the interface may be less ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

Looking to arrange an object by the value of a nested object in Typescript/Angular?

I'm currently developing an Angular 9 application focused on covid-19 cases, and I need to arrange my objects by the value of nested objects. Here is the dataset that I want to organize alphabetically based on the 'state' field values: stat ...

Is it possible to associate a generic TypeScript type with another type by utilizing its generic parameters?

I am faced with a situation where I have a family of APIs consisting of various related generic types (along with associated constraints). To illustrate this, I have crafted an example using familiar types as placeholders for better understanding. As I wo ...

Can you explain the meaning of <T = MyType>?

While exploring a TypeScript file, I stumbled upon this interface declaration: interface SelectProps<T = SelectValue> extends AbstractSelectProps { /* ... */ } I've searched through the TypeScript handbook for <T = but couldn't find an ...

Typescript support on Emacs

"Is there a way to enable Typescript syntax highlighting in Emacs?" I have been struggling with this for quite some time. Using Emacs 24 on an Ubuntu Virtualbox VM, I can't seem to get package-refresh-contents to work as it just hangs on "Contacting ...

I'm having trouble retrieving the value from the textbox in my Angular 7 project using TypeScript

I'm currently working with Angular 7 and trying to create a textbox to display its value in an alert. However, I'm facing difficulty in fetching the textbox value in typescript. I would appreciate any guidance on how to proceed with this issue. ...