当我单击动态创建的复选框时,我得到Cannot find control with name: 'create_param[0]'
的斜角。以下是我正在使用的代码:
exercise-create.ts
{
this.exerciseForm = this.formBuilder.group({
exerciseName: ['', [Validators.required, Validators.maxLength(64)]],
exerciseDescription: ['', [Validators.required, Validators.maxLength(1024)]],
difficulty: ['', Validators.required],
all_params: this.formBuilder.array([this.createItem()])
});
}
createItem(){
return this.formBuilder.group({
param: [''],
})
}
exercise-create.html
<form [formGroup]="exerciseForm" class="col-sm-12" #createExerciseForm>
<div class="field-block" *ngFor="let param of exercise.Params; let id = index;">
<input type="text" formControlName="create_param[{{id}}]"
/>
</div>
</form>
创建复选框
<div *ngFor="let param of customParams">
<input id="{{param.param}}" type="checkbox" [checked]="param.isActive" (change)="updateActiveExercises(param)"/>
</div>
updateActiveExercises(param: any) {
param.isActive = !param.isActive;
this.dirty = true;
let found = false;
const newParams = this.exercise.Params.map((p) => {
found = found || p.param === param.param;
return p.param !== param.param || param.isActive ? p : null;
}).filter(a => a);
if (!found && param.isActive) {
newParams.push(param);
}
this.exercise.Params = newParams;
}
注意::我想对onload创建的元素添加控件,并希望获取它们的值。
任何人都可以提供上述帮助吗?
答案 0 :(得分:1)
您需要在练习组FormForm中添加create_param。
this.exerciseForm = this.formBuilder.group({
exerciseName: ['', [Validators.required, Validators.maxLength(64)]],
exerciseDescription: ['', [Validators.required, Validators.maxLength(1024)]],
difficulty: ['', Validators.required],
all_params: this.formBuilder.array([this.createItem()]),
create_param: [value]
});
答案 1 :(得分:0)
您正在formArray
内使用formGroup
,并且不能将formArray
内的控件视为普通数组中的元素。
<form [formGroup]="exerciseForm" class="col-sm-12" #createExerciseForm>
<div formArrayName="all_params">
<div class="field-block" *ngFor="let form of all_params.controls; let id = index;" [formGroupName]="id">
<input type="text" formControlName="param"/>
</div>
</div>
</form>
formArray
应该被视为formControl
独立主体formGroup
。formArray
遍历*ngFor
,每个项目应被视为formGroup
。formArray
的嵌套控件。在 Angular 中检查有关表单数组的Article。
关注中:
使用formArray参数来实现参数:
get params(): FormArray {
return this.exerciseForm.controls.all_params
}
因此,无论您想在何处获取参数,都不要从this.exercise.Params
中获取它,而应从以前的getter中获取它,例如:this.params
。
将exercise.Params
转换为formArray
onInit
,并在保存时获取params.value
。
您无法遍历原始数组并尝试将其与fromGroup
链接,以上代码中<div .... [formGroupName]="id"> </div>
内的内容代表您的控件,例如:
<div class="field-block" *ngFor="let form of all_params.controls; let id = index;" [formGroupName]="id">
<input formControlName="param" type="checkbox" [checked]="param.value.isActive" (change)="updateActiveExercises(param.value)"/>
</div>