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>