Angular formArray不呈现工作的mat-radio-group

问题描述

这些是不能与formArray一起正常使用的表单元素。它们渲染,但是单击按钮没有任何作用。如果我在其中插入一个断点,则editChoice()事件似乎不会发生。

控件也不会明显改变其按钮状态。

<form [formGroup]="myForm" class="dialogContent">
    <ng-container formArrayName="choices">
        <div class="control" *ngFor="let value of myForm.controls.choices?.value; let i=index">
            <ng-container [formGroupName]="i">
                 <label class="req" [id]="choiceList[i].id + '_label'">
                      {{ choiceList[i].label }}
                 </label>
                 <mat-radio-group attr.aria-label="{{choiceList[i].label}}" 
                  attr.index="{{i}}" 
                  formControlName="choice" [value]=choiceList[i].value?
                  (click)="editChoice($event)"
                  attr.aria-labelledby="{{choiceList[i].id + '_label'}}">
                       <mat-radio-button value="Y">Yes</mat-radio-button>
                       <mat-radio-button value="N">No</mat-radio-button>
                  </mat-radio-group>
             </ng-container>
        </div>
    </ng-container>
</form>

在构造函数中(或在ngInit中,这似乎无关紧要):

this.myForm = this.fb.group({
    otherControl: [''],otherDescription: [''],electronicSignature : ['',[Validators.required]],choices: this.fb.array([]) 
});

要渲染的数组:

choiceList: Array<any> = [
   {
       value: "Y",id: "choiceA",label: "Choice A Text"
   },{
       value: "N",id: "choiceB",label: "Choice B Text"
    } 
    //(and several more like this)
];

在ngInit中:

const choices = this.myForm.controls.choices as FormArray;
for (let i=0; i < this.choiceList.length; i++) {
    choices.push(this.fb.group ({ 
        choice: ['',[Validators.required]]
    }));
}

没有调试错误,除非有某种方法可以打开某些东西以隐藏任何错误

解决方法

显然,模板中的for循环是导致此问题的原因,当您遍历myForm.controls.choices?.controls而不是myForm.controls.choices?.value时,它会起作用。

我真的不能告诉你为什么它不起作用,所以希望有人可以解释一下这里发生的事情。

,

在打字稿端有一个函数将对象作为 FormArray 返回也很有帮助。当您通过 myForm.controls.choices 获取它时,它被输入为控件。

getChoices(): FormArray { 
   return myForm.controls.choices as FormArray; 
} 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...