如何在响应式表单中获取单选按钮的选定值

3
我试图获取单选按钮的selectedValue,并将其作为真实的单选文本传递。如果选择了Choice 1,则将selectedValue发送为true,否则为false。如果选择了Choice 2,则将selectedValue发送为true,否则为false。我无法将其设置为true。想知道是否有人以前做过这个? https://stackblitz.com/edit/angular-xfrezb
2个回答

0

你正在混淆表现视图和表单的值。我认为最好分开这些概念。我们可以使用formObj来创建表现形式,使用callbackForm来处理值。请查看代码中的注释。

//app.main.html

<form [formGroup]="callbackForm" (submit)=submit(callbackForm)>
  <div>
    <div formArrayName="componentDetails">
        <div *ngFor="let question of callbackForm.controls.componentDetails.controls; let i = index;" [formGroupName]="i">
            <div class="row">
                <div class="col-md-12 panel-group panel-group--compressed">
                    <div class="panel panel--default">
                        <fieldset>
<!--see that we create the "view of the form using formObj.componentDetails--!>
                            <div class="row" *ngIf="formObj.componentDetails[i].type === 'radio'">
                                <div class="col-md-12">
                                    <p>{{ formObj.componentDetails[i].label }}</p>
                                    <p>{{ formObj.componentDetails[i].cpv }}</p>
<!-- we iterate throught "formObj.componentDetails[i].component -->
<!-- again, we are using formObj to the "view" -->
                                    <div *ngFor="let answer of formObj.componentDetails[i].component; let j = index">
                                       <label class="radio radio--alt radio--stacked">
                                            <span class="radio__input"></span>
                                             <span class="radio__label">{{ answer.value }}</span>
                                        </label>
<!--We have a input with name=formObj.componentDetails[i].cpv -->
<!--it's necesary enclose between {{ }} the name -->
                                        <input type="radio" formControlName="{{formObj.componentDetails[i].cpv}}" [value]="answer.selectedValue">
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<button type="submit">send</submit>
</form>
<pre>{{callbackForm.value | json}}</pre>

//app-main.component

@Component({
  selector: 'app-app-main',
  templateUrl: './app-main.component.html'

})
export class AppMainComponent {

  constructor(private _formBuild: FormBuilder) {}

  ngOnInit() {
    this.loadObservableForm();
  }

  public callbackForm: FormGroup;

  formObj = {
    "componentDetails": [{
      "component": [{
        "value": "Choice 1",
        "selectedValue": true
      }, {
        "value": "Choice 2",
        "selectedValue": false
      }],
      "cpv": "name1",  //<--we use this to create the name of the fileld
      "label": "Description of Problem",
      "type": "radio",
      "mandatory": true
    }]
  };

  loadObservableForm() {
    this.callbackForm = this._formBuild.group({
      componentDetails: this._formBuild.array([])
    });
    this.addComponentDetails();
  }

  addComponentDetails() {
    const control = <FormArray>this.callbackForm.controls.componentDetails;
    this.formObj.componentDetails.forEach(x => {
      control.push(this.addControl(x));
    });
  }

  addControl(x) {
    //we create a group control with a control with a name "x.cpv"
    const group = this._formBuild.group({});
    group.addControl(x.cpv,new FormControl());
    return group;
  }

我们在"componentDetails"中有一个回调表单,格式为[{"name1": false},{"name2":value2}...]。因此,在提交时我们可以执行以下操作:

submit(form)
{
   if (form.valid)
   {
       let response:any={}
       for (let control of form.value.componentDetails)
          response={...response,...control}

       console.log(response);
   }
}

谢谢Eliseo。将formObj和callbackForm分开是一个有趣的概念,我也会尝试一下。 - David Jeyathilak

0

首先,在您的问题中始终包含相关代码块,因为链接往往会随着时间而失效...

但是对于您的问题,由于您正在处理多个问题和动态value,我会传递当前的formArray components和当前的answer。然后,您需要首先将所有表单控件selectedValue设置为false,否则每次切换单选按钮时,每个单选按钮最终都会变为true。因此,在首先将所有内容设置为false之后,只需将所选单选按钮设置为true即可。因此,请执行以下操作:

<div *ngIf="question.controls.type.value === 'radio'">
  <p>{{ question.controls.label.value }}</p>
  <div formArrayName="component">
    <div *ngFor="let answer of question.controls.component.controls; 
                 let j = index" [formGroupName]="j">
      <label>
        <input type="radio" name="radio-stacked" 
           (click)="updateSelection(question.controls.component.controls, answer)">
          <span>{{ answer.value.value }}</span>
      </label>
    </div>
  </div>
</div>

然后是你的updateSelection方法:

updateSelection(formArr, answer) {
  formArr.forEach(x => {
    x.controls.selectedValue.setValue(false);
  });
  answer.controls.selectedValue.setValue(true);
}

你的分支StackBlitz

顺便说一句,你可以考虑的一件事是,在你的表单对象中不要包含所有选项,而只需添加你选择的单选按钮的值。


谢谢Alex!太棒了,正是我想要的。我不知道我必须使用setValue。我需要发送表单对象中的所有选择...这样后端Java开发人员就知道确切的选择和选定的值来更新数据库...再次感谢! - David Jeyathilak
非常欢迎!是的,如果我们需要设置表单控件的值,我们需要使用 setValue。或者,如果您有一个表单组,并且想要设置属于该表单组的某些值,您可以使用 patchValuethis.myForm.patchValue({ ... })。如果您在相同的情况下使用 setValue,则需要为该表单组中的所有表单控件提供所有值。但是,很高兴听到这个解决方案对您有效! :) 祝您周末愉快 :) - AT82
嗨@Alex - 非常感谢您在单选按钮的值方面提供的帮助..我无法使下拉框工作相同。您能帮忙吗?https://dev59.com/Qajka4cB1Zd3GeqPBqHI - David Jeyathilak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接