Attempting to grasp the concept of implementing FormArray

When I execute the following code:

this.formArray = new FormArray([
  new FormControl(''),
  new FormControl(''),
]);

formControlA() {
  return this.formArray.at(0);
}

formControlB() {
  return this.formArray.at(1);
}

and then use it in a template like this:

<mat-select [formControl]="formControlA>...</mat-select>
<mat-select [formControl]="formControlB>...</mat-select>

I encounter the following error:

Type 'AbstractControl<any, any>' is missing the following properties from type 'FormControl': defaultValue, registerOnChange, registerOnDisabledChange

I am confused as to why the .at() method on FormArray returns an AbstractControl instead of a FormControl, which was the type it was created with. Why is there a discrepancy?

I thought that using casting was discouraged? How can I achieve the desired outcome without relying on what could be considered bad casting?

formControlA() {
  return this.formArray.at(0) as unknown as FormControl;
}

Answer №1

An AbstractControl has a minimum of 3 built-in subclasses :

  • FormControl
  • FormArray
  • FormGroup

In certain scenarios, this.formArray.at(0) may appropriately yield a FormGroup or FormArray (e.g. when nesting forms).

Since the type of this.formArray.at(0) cannot be guaranteed to be a FormControl, casting becomes necessary.

There is one exception: if you already know the quantity of FormControl elements (although it's unclear why a FormArray would be needed in such a scenario), you can still create individual instances of FormControl:

formControlA = new FormControl();
formControlB = new FormControl();
formArray = new FormArray([formControlA, formControlB])

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

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Angular drag and drop functionality combined with interactive buttons for list management

Looking to create an Angular component for re-sorting objects by dragging from one list to another? I also need this component to include buttons for additional functionality. I've explored the various drag and drop components available on the Angula ...

Annoying border problem encountered with Angular material column header

After upgrading Angular Material to version 9, I encountered an issue where a bottom border appears under the sorted column heading in my mat-table. Strangely, the border disappears when clicked upon. Upon inspecting the browser's CSS, I discovered t ...

Determining the Best Option: React JS vs Angular UI Framework

After researching the latest versions of React and Angular online, I discovered that both are suitable for developing Web Application UI. However, I also realized that there are key differences to consider when choosing between the two. Let's say I h ...

How can dependencies for an entire class or module be mocked in the mocha ecosystem similar to jest.mock?

I am currently working on unit testing a module that resembles the following code structure: import { Countdown } from "./database/orm"; export class PersistentTimer { protected constructor(...) { ... } // To ensure database writing ...

The Angular router is throwing a "TS2339: Property 'navigate' does not exist on type 'Route'." error message

I'm really struggling with this issue. Why is the 'navigate' property not available to use? When attempting to use it, I receive the error message "TS2339: Property 'navigate' does not exist on type 'Route'." For more in ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

Intellisense in VSCode is failing to suggest subfolder exports

In my setup, I have a repository/module specifically designed to export TypeScript types into another project. Both of these projects are using TypeScript with ECMAScript modules. The relevant part of the tsconfig.json configuration is as follows: "ta ...

Using $gte and $lt to search within a range in mongoDB can be tricky when dealing with data types in typescript

Whenever I try to search by range of dates using $gte and $lt, I encounter issues with types. The types for my model are as follows: export interface IOneStoreCa { magId: number, caTtc?: number, marge?: number, } export interface ICa { _id: string ...

Issue encountered when using Angular CLI to generate new files in the current directory

I've encountered an issue where, when using Angular CLI to generate components, it places them in the App folder instead of the current directory. For example, if I navigate to App/Recipe and run "ng g c recipe-item", the component will be generated i ...

The ngFor directive in Angular should be used with the Filter pipe to ensure that

Having a Filter implemented in my Angular Project that fetches data from Firebase. The current status in the Filter is as follows: Name 1: Lea Muster Name 2: Bruno Mustermann Name 3: Lea Muster Name 4: Gabriela Musterfrau The goal is to show duplicate e ...

Unable to access the FormControl instance directly. It is not possible to read the property 'invalid' of an undefined value

Accessing in Angular docs is not the same as before, you must first grab the FormGroup instance and then find the FormControl instance within it. I wonder why? This example works: <form [formGroup]="myForm" (ngSubmit)="onSubmit()"> <div class=" ...

Angular Materials auto-complete - Presenting choices depending on certain criteria

I have implemented 4 components, each containing a material autocomplete feature with the same set of options. Whenever I select an option in one component, it sets isAvailable to false and disables that option in the other components. The array below show ...

To work on React with typescript, your Type must include a method '[Symbol.iterator]()' that will fetch an iterator

Here is a demonstration I have prepared for you: https://stackblitz.com/edit/react-ts-shopping-cart-ssofgc?file=Shop.tsx Apologies for the lack of clarity in my question, but... The demo I created showcases a basic shopping cart using React and Typescri ...

Which delivers better performance: HTTP request from server or client?

Considering the optimal performance, is there a difference in using Angular's HTTP request within a MEAN-stack environment compared to utilizing Request.js or similar for server requests? ...

Do I need to use Node.js for Angular 2, or can I run it on an Apache server instead

Can XAMPP or Apache be used instead of the Node.js npm server when working with Angular 2? ...

Get detailed coverage reports using Istanbul JS, Vue JS, Vue CLI, Cypress end-to-end tests, and Typescript, focusing on specific files for analysis

I have a VueJS app written in Typescript that I am testing with Cypress e2e tests. I wanted to set up coverage reports using Istanbul JS to track how much of my code is covered by the tests. The integration process seemed straightforward based on the docum ...

Old version of Nativescript appium testing being installed ORAn outdated

I am in the process of creating a mobile application using nativescript + angular, and I am currently testing it with Appium. However, when I execute end-to-end tests using the following command, it seems to load an older version of my app. tns build andr ...

What is the best way to utilize yarn in order to install a GitHub package that utilizes TypeScript and has not yet been compiled?

After making modifications to an npm package and using yarn link <project name> locally, everything works perfectly. However, when pushing it to GitHub and trying to add it to the project with yarn add <repo url>#<branch> instead of yarn ...

Can we securely retrieve nested properties from an object using an array of keys in TypeScript? Is there a method to accomplish this in a manner that is type-safe and easily combinable?

I wish to create a function that retrieves a value from an object using an array of property keys. Here's an example implementation: function getValue<O, K extends ObjKeys<O>>(obj: O, keys: K): ObjVal<O,K> { let out = obj; for (c ...