samedi 15 août 2020

Cannot find control with name: '0'

I have to make a form consisting of a series of dynamically created check buttons. I was inspired by the code taken from a site, but it always gives me this error: "Cannot find control with name: '0'". How can I solve it? Thank you all!

Code typescript:

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);
  }

}

Code HTML:

<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> </td>
                </tr>
            </tbody>
        </table>
        <button class="special rounded-pill" > Inserisci </button>
    </form>
</div>



Aucun commentaire:

Enregistrer un commentaire