在模板中生成时动态添加formControl

时间:2019-10-22 20:30:41

标签: angular typescript django-rest-framework angular-material angular-reactive-forms

我正在开发一个应用程序,该应用程序从存储在django REST API后端中的真实世界人口统计调查中收集到一系列问题和答案。我已根据调查问题类别(即与健康,人口统计学,收入等有关的问题)将调查分为多个部分。特定的建议答案问题具有唯一的ID,这些ID指向问题ID和调查ID,并且还具有“类型”属性,该属性指示答案是否要求提供金额,文本等。父级“调查”部分具有子级通过@Input继承父级“ FormGroup”的“类别”组件。

salud.component.html

<form [formGroup]="encuestaHogarForm" class="container">
    <!-- primary questions -->
  <div *ngFor="let textoPregunta of preguntasUnicas; let i = index">
    <h3 id="label{{i}}">{{textoPregunta}}</h3>
    <ng-container *ngFor="let p of preguntas">
      <ng-container *ngIf="textoPregunta === p.preguntaxencuesta.pregunta.texto_pregunta">
        <!-- primary answers that belong to a question -->
        <span [ngSwitch]="p.tipo">
          <p *ngSwitchCase="'B'">
            <mat-radio-button name="rbRes{{p.preguntaxencuesta.id}}" aria-labelledby="label{{i}}"
              formControlName="valorRP{{p.id}}">{{p.respuesta_propuesta.texto_respuesta}}</mat-radio-button>
          </p>
          <p *ngSwitchCase="'C'">

          </p>
          <!-- secondary questions that belong to a primary question-answer -->
          <ng-container *ngFor="let p2 of preguntasSecundarias"> 
            <ng-container *ngIf="p2.preguntasecundariaxresp.preguntaxencuestaxrespuesta.id === p.id">
              <mat-form-field *ngIf="p2.tipo === 'C'">
                <input matInput placeholder="{{p2.preguntasecundariaxresp.pregunta_secundaria.texto_pregunta}}">
              </mat-form-field>
            </ng-container>
          </ng-container>
        </span>
    </ng-container>
  </ng-container>
</div>
</form>

我希望将formControlName分配给动态生成的mat-radio-button,以便能够将其添加到我的encuestaHogarForm父表单中。我已经考虑过使用FormArray,但是我不知道如何动态地将在DOM中创建的元素推入FormArray

我尝试在component.ts中以相同的方式分配formControlName="valorRP{{p.id}}"

salud.component.ts

...

getPreguntas(): void {
    this.encuestaService.getPreguntasPrimariasPorCategoria(this.categoria)
      .subscribe(preguntas => {
        this.preguntas = preguntas;
        this.preguntasUnicas = [...new Set(preguntas.map(array => array.preguntaxencuesta.pregunta.texto_pregunta))];
        this.preguntasUnicas.forEach(textoPregunta => {
          this.preguntas.forEach(p => {
            if (textoPregunta === p.preguntaxencuesta.pregunta.texto_pregunta) {
              this.encuestaHogarForm.addControl('valorRP' + p.id, new FormControl()); // Attempts to register the controls
              this.preguntasSecundarias.forEach(p2 => {
                if (p2.preguntasecundariaxresp.preguntaxencuestaxrespuesta.url === p.url) {
                  //console.log('- ' + p2.preguntasecundariaxresp.pregunta_secundaria.texto_pregunta);
                }
              });
            }
          });
        });
      });
  }

...

但是,这无法按预期工作,因为我认为它正在尝试在创建之前在DOM中找到formControlName

1 个答案:

答案 0 :(得分:1)

Jose,请确保您要初始化formGroup

encuestaHogarForm=new FormGroup({})

MoreOver,您还可以遍历encuestaHogarForm.controls |键值,而不是遍历preguntasUnicas,例如。简单stackblitz

<button (click)="add()">Add</button>
<form [formGroup]="myForm">
  <div *ngFor="let control of myForm.controls|keyvalue;let i=index" >
    {{questions[i]}}
       <input [formControl]="myForm.get('valorRP'+i)">
  </div>
</form>

  myForm=new FormGroup({})
  questions=["uno","dos","tres","cuatro"]
  add()
  {
    const index=Object.keys(this.myForm.controls).length
    this.myForm.addControl('valorRP'+index,new FormControl(null))
  }