【问题标题】:Property 'controls' does not exist on type 'AbstractControl'. Angular 6“AbstractControl”类型上不存在属性“控件”。角 6
【发布时间】:2019-03-07 07:55:59
【问题描述】:

当我们在 for 循环中使用 setvalue 时。

一切都很好,但它给出了错误:-

“AbstractControl”类型上不存在属性“控件”。

角度 6 我们如何解决这个问题..

for (let i = 0; i < this.experience.length; i++) 
  { 
     if ( i !== 0 ){ 
       const control = <FormArray>this.expGroup.controls['expArray'];
       control.push(this.getExp()); 
     }
  this.expArray.at(i).controls['company_Name'].setValue(this.experience[i].company_Name);
  this.expArray.at(i).controls['position'].setValue(this.experience[i].position); 

  this.expArray.at(i).controls['employee_id'].setValue(this.experience[i].employee_id); 

  this.expArray.at(i).controls['time_prefered'].setValue(this.experience[i].time_prefered);   this.expArray.at(i).controls['work_exp_year'].setValue(this.experience[i].work_exp_year);   this.expArray.at(i).controls['date_of_joining'].setValue(this.experience[i].date_of_joining);   
  this.expArray.at(i).controls['id'].setValue(this.experience[i].id);    
}

【问题讨论】:

  • this.expArray 的值是多少?是表单数组吗?
  • 在这种情况下最好使用getter,例如this.expGroup.get(expArray.${index}.company_Name).setValue(this.experience[i].company_Name)
  • 是的,它是一个表单数组
  • 我会尝试,但效果很好。
  • 非常感谢先生,这样做后它的工作正常 this.expArray.at(i).get('company_Name').setValue(this.experience[i].company_Name);

标签: angular typescript angular6


【解决方案1】:

建议使用 getter 从 FormArray 访问所需控件,而不是直接访问每个 FormArray 元素的 controls 属性。在通过索引迭代FormArray 时,它将每个数组元素公开为AbstractControl 的类型,它直接无法访问controls 属性。因此,您可以使用以下代码 -

this.expArray.at(i).get('company_Name').setValue(this.experience[i].company_Name);

为 FormArray 中的每个控件设置值。

这是完整的代码-

    for (let i = 0; i < this.experience.length; i++) 
      { 
         if ( i !== 0 ){ 
           const control = <FormArray>this.expGroup.controls['expArray'];
           control.push(this.getExp()); 
         }
     this.expArray.at(i).get('company_Name').setValue(this.experience[i].company_Name); 
     this.expArray.at(i).get('position').setValue(this.experience[i].position); 

     this.expArray.at(i).get('employee_id').setValue(this.experience[i].employee_id); 

     this.expArray.at(i).get('time_prefered').setValue(this.experience[i].time_prefered);
     this.expArray.at(i).get('work_exp_year').setValue(this.experience[i].work_exp_year);
     this.expArray.at(i).get('date_of_joining').setValue(this.experience[i].date_of_joining);   
     this.expArray.at(i).get('id').setValue(this.experience[i].id);    

   }

【讨论】:

  • setValue 到复选框有一些问题。我会为你提供 stackblitz 链接以供审查。
猜你喜欢
  • 2019-04-11
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 2023-03-03
  • 2018-01-26
  • 2021-08-13
  • 1970-01-01
  • 2019-10-10
相关资源
最近更新 更多