In Ionic 2 I am trying to create a dynamic form which shall display a list of toggle buttons.
To do so I am trying to use a FormArray and relied on the Angular doc and mainly on this post
Based on this, I implemented the following
<form *ngIf="accountForm" [formGroup]="accountForm">
<ion-list>
<!-- Personal info -->
<ion-list-header padding-top>
Informations personnelles
</ion-list-header>
<ion-item>
<ion-label stacked>Prénom</ion-label>
<ion-input formControlName="firstname" [value]="(user | async)?.info.firstname" type="text"></ion-input>
</ion-item>
<!-- Sport info -->
<ion-list-header padding-top>
Mes préférences sportives
</ion-list-header>
<ion-list formArrayName="sports">
<ion-item *ngFor="let sport of accountForm.controls.sports.controls; let i = index" [formGroupName]="i">
<ion-label>{{sport.name | hashtag}}</ion-label>
<ion-toggle formControlName="{{sport.name}}"></ion-toggle>
</ion-item>
</ion-list>
</ion-list>
</form>
Controller
ionViewDidLoad() {
console.log('MyAccountPage#ionViewDidLoad');
// Retrieve the whole sport list
this.sportList$ = this.dbService.getSportList();
this.sportList$.subscribe(list => {
// Build form
let sportFormArr: FormArray = new FormArray([]);
for (let i=0; i < list.length; i++) {
let fg = new FormGroup({});
fg.addControl(list[i].id, new FormControl(false));
sportFormArr.push(fg);
}
this.accountForm = this.formBuilder.group({
firstname: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])],
lastname: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])],
company: [''],
sports: sportFormArr
});
console.log('form ', this.accountForm);
})
}
But I get the following error:
ERROR Error: Cannot find control with path: 'sports -> 0 -> '
Here is the content of accountForm
Any idea why ?
formControlName="{{sport.name}}"
. I bet the error is with this. – Gynecocracy