Angular formArray 不渲染工作垫子无线电组



这些表单元素不能正确使用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上循环时,它会起作用。

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

在typescript端有一个函数,它将对象作为FormArray返回,这也有助于实现。当您通过myForm.controls.choice获取它时,它被键入为控件。

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

最新更新