You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 4中动态创建formControlName?附组件实现代码

动态生成formControlName的解决方案

我来帮你搞定这个动态生成formControlName的问题~你当前的代码里有个小细节没处理对:在initAddress方法里,你定义了ans变量,但直接在FormGroup的对象字面量里写ans: ['']的话,它会把字符串'ans'当成固定键名,而不是你想要的is_answer_0、is_answer_1这类动态值。

修改控制器代码

只需要把FormGroup的键名改成方括号语法[ans],就能用变量的值作为动态键名了:

ngOnInit() {
  this.rForm = this.fb.group({
    question_type_id: this.fb.array([]),
  });
  for (let i = 0; i < this.getQuestionsType.length; i++) {
    const control = <FormArray>this.rForm.controls['question_type_id'];
    control.push(this.initAddress(i));
  }
}

initAddress(i: number) {
  const ans = `is_answer_${i}`;
  // 用方括号语法绑定动态键名
  return this.fb.group({
    [ans]: ['']
  });
}

模板中绑定动态formControlName

接下来在模板里,遍历question_type_id这个FormArray,针对每个FormGroup绑定对应的动态键名即可:

<form [formGroup]="rForm">
  <div formArrayName="question_type_id">
    <!-- 遍历FormArray里的每个FormGroup -->
    <div *ngFor="let group of rForm.get('question_type_id').controls; let i = index" [formGroup]="group">
      <!-- 直接拼接出动态的formControlName -->
      <input 
        type="text" 
        [formControlName]="'is_answer_' + i"
        placeholder="输入答案 {{i}}"
      >
    </div>
  </div>
</form>

这样就能完美生成is_answer_0、is_answer_1这类符合你需求的动态formControlName啦~

内容的提问来源于stack exchange,提问作者Apurv Chaudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:34:21