在Ionic 2中,我试图创建一个动态表单,该表单将显示切换按钮列表。
为此,我正在尝试使用FormArray,它依赖于Angular文档,主要依赖于这个post
基于此,我实现了以下内容
<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>控制器
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);
})
}但我得到以下错误:
ERROR Error: Cannot find control with path: 'sports -> 0 -> '下面是accountForm的内容

知道为什么吗?
发布于 2017-06-01 22:25:14
我不知道如何/是否可以获得动态创建的name控件的属性名称……但是您可以使用您已有的列表,您可以从该列表中构建表单组。然后,您只需将要获取的列表分配给一个局部变量,以便您可以在模板中使用它。
首先,如果您想使用这项运动的name,您需要更改您的创建表单组,并使用name而不是id:
我会稍微调整一下结构,为formarray使用一个getter,这样做:
// choose better name ;)
get formArr() {
return this.accountForm.get("sports") as FormArray;
}在本例中,fb指的是FormBuilder:
this.accountForm = this.fb.group({
sports: this.fb.array([])
});
// ...........
// don't use any, type your data!
this.list.forEach((item: any, i) => {
this.formArr.push(
this.fb.group({
[this.list[i].name]: false
})
);
});如上所述,您可以使用模板中的列表和索引,因此:
<ion-item *ngFor="let sport of formArr.controls; let i = index" [formGroupName]="i">
<ion-label>{{list[i].name}}</ion-label>
<ion-toggle [formControlName]="list[i].name"></ion-toggle>
</ion-item>这是一个带有(唯一) angular的
https://stackoverflow.com/questions/44308795
复制相似问题