Angular formArray单选按钮 [英] Angular formArray radio buttons

查看:86
本文介绍了Angular formArray单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将单选按钮组添加到FormArray.问题是,当我选择一个值时,它将更改FormArray的每个成员的值.我知道这与formControlName有关,但是我不知道如何使formControlName动态化.我看过这篇文章,但是它已经4岁了有点模糊即,我无法从中得出明确的答案.

I am attempting to add a radio button group to a FormArray. The issue is that when I select a value, it changes the value for every member of the FormArray. I know this has to do with the formControlName, but I don't know how to make the formControlName dynamic. I've looked at this post but it's 4 years old and a little vague; i.e., I couldn't come to a clear answer therefrom.

这是我目前拥有的:

//inputs and variable initialization

ngOnInit() {
  this.createSensorForm();
}

createSensorForm() {
    this.sensorForm = this.fb.group({
      ...
      definitions: this.fb.array([this.createDefinition()])
  });
}

createDefinition(): FormGroup {
  return this.fb.group({
    numeric: [""],
  });
}

addDefinition() {
  this.definitions = this.sensorForm.get('definitions') as FormArray;
  this.definitions.push(this.createDefinition());
}

HTML组件

<form [formGroup]="sensorForm" (ngSubmit)="createSensor()">
  ...
  <div formArrayName="definitions" 
       *ngFor="let definition of sensorForm.get('definitions').controls; let i = index;">
    <div [formGroupName]="i">
      ...
      <input type="radio" [value]="true" 
             formControlName="numeric" [(ngModel)]="numeric"> Yes
      <input type="radio" [value]="false" 
             formControlName="numeric" [(ngModel)]="numeric"> No
    </div>
  </div>
    <button class="btn btn-primary" type="button" (click)="addDefinition()">
      <i class="fa fa-plus"></i> Add Definition
    </button>
</form>

推荐答案

<div *ngIf="sensorForm"  [formGroup]="sensorForm" (ngSubmit)="createSensor()>
  <!---first the name of array-->
  <div formArrayName="definitions">
      <!--after the loop using a div, this div has [fromGroupName]=i -->
      <div *ngFor="let definition of sensorForm.get('definitions').controls; 
                  let i = index;" [formGroupName]="i">
          <!--each element, only use formControlName, ¡NOT! [(ngModel)] -->
          <!-- ngModel is for Template driven Form  -->
          <input type="radio" [value]="true" formControlName="numeric" > Yes
          <input type="radio" [value]="false" formControlName="numeric" > No
      </div>
  </div>  
</div>

您的addDefinition错误,您没有"this.definitions"

Your addDefinition is wrong, you have not "this.definitions"

addDefinition() {
    const definitions = this.sensorForm.get('definitions') as FormArray;
    definitions.push(this.createDefinition());
  }

这篇关于Angular formArray单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆