【问题标题】:Angular formArray doesn't render working mat-radio-groupAngular formArray 不呈现工作的 mat-radio-group
【发布时间】:2021-02-04 14:58:54
【问题描述】:

这些表单元素不能与 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]]
    }));
}

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

【问题讨论】:

  • 这看起来很奇怪:formControlName="choice" [value]=choiceList[i].value? (click)="editChoice($event)"
  • 如果我将其中的任何一项关闭,它仍然无法正常工作。无论如何,我是从一个工作示例中得到的。 formControlName="choice" [value]=choiceList[i].value? (click)="editChoice($event)"
  • 我的意思是,这个位没有引号并以 ? 结尾[值]=选择列表[i].值? - 尝试 [value]=“choiceList[i].value”

标签: angular formarray


【解决方案1】:

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

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

【讨论】:

  • 至少有人可以指出一个工作示例。我可以让 Angular 使用普通控件(如基本单选按钮)循环工作,但它似乎会与更复杂的项目(如垫子设计的东西)混淆
  • 我复制了您的完整示例并将value 切换为controls,这对我有用,也许您的代码中还有其他错误?
  • 你能点击控件吗?它们渲染但不起作用。
  • 是的,value 渲染但没有工作,但 controls 工作正常
  • 我认为我的问题是我在数组列表中有非控件。后来我得到了类似的工作。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-12-22
    • 2020-12-01
    • 1970-01-01
    • 2021-10-29
    • 2020-05-29
    • 1970-01-01
    • 2018-08-07
    • 2018-12-16
    • 2018-10-11
    相关资源
    最近更新 更多