找不到名称为“ create_param [0]”的控件

时间:2019-10-01 05:25:37

标签: angular

当我单击动态创建的复选框时,我得到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创建的元素添加控件,并希望获取它们的值。

任何人都可以提供上述帮助吗?

2 个答案:

答案 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>