The specified control named '0' could not be located

I need to create a form with dynamically generated check buttons. I tried using code from a website as inspiration, but I keep getting an error message saying: "Cannot find control with name: '0'". Can anyone help me troubleshoot this issue? Thank you in advance!

Here is the Typescript code snippet:

import { Component, OnInit, Input } from '@angular/core';import { FiguraProfessionale } from 'src/app/model/FiguraProfessionale';
import { FiguraProfessionaleCompetenza } from 'src/app/model/FiguraProfessionaleCompetenza';
import { Competenza } from 'src/app/model/Competenza';
import { AssociaFiguraProfessionaleCompetenzeServiceService } from '../associa-figura-professionale-competenze-service.service';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, FormArray, FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-associa-figura-professionale-competenze',
  templateUrl: './associa-figura-professionale-competenze.component.html',
  styleUrls: ['./associa-figura-professionale-competenze.component.css']
})
export class AssociaFiguraProfessionaleCompetenzeComponent implements OnInit {

  figuraProfessionaleCompetenza: FiguraProfessionaleCompetenza;

  listaFiguraProfessionale: Array<FiguraProfessionale>;

  listaCompetenza: Array<Competenza>;

  form: FormGroup;

  constructor(private formBuilder: FormBuilder, private servizio: AssociaFiguraProfessionaleCompetenzeServiceService, private route: Router) {
    this.form = this.formBuilder.group({
      competenzeScelte: new FormArray([])
    });
    this.figuraProfessionaleCompetenza = new FiguraProfessionaleCompetenza();
    this.listaCompetenza = JSON.parse(sessionStorage.getItem("listaCompetenza"));
    this.listaFiguraProfessionale = JSON.parse(sessionStorage.getItem("listaFiguraProfessionale"));
    this.addCheckboxes();
  }

  get competenzeFormArray() {
    return this.form.controls.competenzeScelte as FormArray;
  }

  private addCheckboxes() {
    this.listaCompetenza.forEach(() => this.competenzeFormArray.push(new FormControl(false)));
  }

  ngOnInit(): void {
  }

  inserisci() {
    const competenzeSelezionate = this.form.value.competenzeScelte
      .map((checked, i) => checked ? this.listaCompetenza[i].id : null)
      .filter(v => v !== null);
    console.log(competenzeSelezionate);
  }

}

Here is the HTML code snippet:

<div class="form-group">
    <form [formGroup]="form" (ngSubmit)="inserisci()">
        <table>
            <tbody>
                <tr *ngFor="let competenza of competenzeFormArray.controls; let i = index">
                    <td><input type="checkbox" [formControlName]="[i]"></td>
                    <td>{{listaCompetenza[i].codice}} {{listaCompetenza[i].descrizione}}</td>
                </tr>
            </tbody>
        </table>
        <button class="special rounded-pill" > Inserisci </button>
    </form>
</div>

Answer №1

Don't forget to include the form array name in your HTML code.

Make sure to add

formArrayName="competenzeScelte"
in your HTML like this.

<tr formArrayName="competenzeScelte" *ngFor="let competenza of competenzeFormArray.controls; let i = index">

By doing this, you will be able to resolve your issue.

Answer №2

This solution saved the day for me, so I thought I'd share it here.

<div formArrayName="categoryEntries">
     <div *ngFor="let entry of categoryEntries.controls; let i = index" [formGroupName]="i">
         <!-- your content goes here -->
     </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

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

Creating uniform-sized cards with CSS and Bootstrap

Is there a way to ensure consistent card size across all lines? I've noticed that the cards in the second line are taller. Can we base the height of all cards on this? https://i.sstatic.net/KgZwu.png Below is the HTML code: <div class="row"&g ...

The error message "Duplicate identifier readonly" occurs in TypeScript when there are multiple declarations of a property named Constants.read

I have implemented the following code in utils -> Constants.ts for my Angular project. Constants.ts export class Constants { static readonly LOCAL_STORAGE = 'LOCAL_STORAGE'; static readonly SESSION_STORAGE = 'SESSION_STORAG ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

Error message stating: "A missing module (MODULE_NOT_FOUND) was detected in the nest.js code

Having a code base that runs smoothly on a Windows machine using node v10.16.3, I encountered an issue when trying to install the same code on a CentOS Linux box with node v12.16.3. The error message displayed is regarding a missing module '@angular-d ...

Keyhole Markup Language (KML) - a specialized layer for mapping

Is there a way to create a KML layer for a polygon with specific coordinates in such a way that the area outside of the polygon is disabled from being clicked or utilized by drawing managers? [33.832681,-84.504041], [33.889129,-84.361905],[33.756788,-84. ...

Unleashing the power of DOM events through jQuery observables

I'm a bit confused at the moment. I'm working with an Angular project using a Bootstrap theme. Someone has implemented tab functionality using Bootstrap, but there's an issue - it's all written in JavaScript. This means that events such ...

Looking for nested objects within an array in JavaScript

Currently, I am dealing with a REST API that provides data in the following format: students = [{ batch_id: 22 id: 1 image: null name: "a new batch student", attendance: [ { id: 1, student_id: 1, batch_id: 22, absent_on: "2019-09-15", ti ...

What is the best way to adjust the z-index (greater than 1000) of ngx-material-timepicker within a Material Dialog (MatDialog)?

When the ngx-timepicker-field is inside a MatDialog, it appears behind the modal popup of the dialog. constructor(public dialog: MatDialog) { } const dialogRef = this.dialog.open(PopupComponent, { data: { ... }, position: { to ...

Angular 6: showcasing details of selected dropdown items seamlessly on the current page

I am completely new to Angular and I am facing a challenge in displaying another component on the same page. The concept is to select an option from a dropdown menu and then receive detailed information about it below the dropdown on the very same page. No ...

Send over the necessary props containing the todoListId to the component

I am currently working on a Todo project, where I need to create tasks by passing three elements to the task API: "todoListId", "title", and "content". However, I am facing an issue with passing the "todoListId" element. How can I achieve this? In my cod ...

Is it possible for the navigator to provide the language or languages used in Angular Universal?

I am curious about the use of navigator in code that is meant to run on the server, as navigator is typically used in browser environments. In a codebase at work, I came across the following snippet: navigator.language.slice(0, 2); Interestingly, we are u ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...

Incorporate a JavaScript array into a TypeScript document

Having a file named array.js with a large collection of strings, structured like this: module.exports = ["word1","word2",...] I attempted to utilize this array in my validation.ts file by adding the following line: let wiki = require('./array.js&a ...

cutting the limit of table rows in Angular by half

I have an array called carsList with 5 values. I am trying to slice it 2 by 2. <table> <tr *ngFor="#item of carsList | slice:0:2; #i = index"> <td>{{i}}. {{item}}</td> </tr> </table> The code above is o ...

Angular 10 does not fulfill promises as expected

In the Angular 10 project I'm working on, I encountered an issue while trying to call an API request asynchronously using promises. The code I wrote didn't seem to execute the API call as expected and kept exiting at the first line without progre ...

Passing data between two Angular directives using EventEmitter

Looking to share a variable between two directives in Angular 7 Check out the updated code here: https://stackblitz.com/edit/angular-ct49bn The issue arises when selecting a customer from the list, as the emitter fails to communicate with the other direc ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...

I'm having trouble with ViewChild - consider upgrading to beta7 for a solution

import {Page,NavController,NavParams,Platform,IonicApp} from 'ionic-angular'; import {ViewChild} from '@angular/core'; @Page({ templateUrl: 'build/pages/tabspage/tabspage.html' }) @ViewChild('myTabs') tabRef: T ...