【问题标题】:how to get selected value of radio in reactive form如何以反应形式获取选定的无线电值
【发布时间】:2018-07-06 09:53:42
【问题描述】:

我正在尝试获取单选按钮的 selectedValue 并将其作为 true 与单选文本一起传递。如果选择了选项 1,则 selectedValue 作为 true 发送,否则为 false。如果选择了选项 2,则 selectedValue 发送为 true,否则发送 false。我无法将其设置为 true。想知道以前有没有人这样做过?

https://stackblitz.com/edit/angular-xfrezb

【问题讨论】:

    标签: angular radio-button angular-reactive-forms formarray


    【解决方案1】:

    首先,始终将问题中的相关代码作为代码块包含在内,因为链接往往会随着时间的推移而消失...

    但至于您的问题,由于您正在处理几个问题和动态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

    PS,您当​​然可以考虑做的,不是在您的表单对象中拥有所有选项,而只是添加您选择的单选按钮的值。

    【讨论】:

    • 谢谢亚历克斯!太棒了,正是我想要的。不知道我必须使用 setValue。我需要发送表单对象中的所有选择。所以后端 Java 开发人员知道更新数据库的确切选择和选择的值。再次感谢!
    • 不客气!是的,总是为表单控件设置值,我们需要使用setValue。或者,例如,如果您有一个表单组并且只想设置属于该表单组的一些值,您可以使用patchValuethis.myForm.patchValue({ ... }) 如果您要在同一场景中使用setValue,则需要提供所有值对于该表单组中的表单控件。但是,是的,很高兴听到这个解决方案对您来说是可行的! :) 周末愉快 :)
    • 嗨@Alex - 非常感谢您在无线电选择值方面的帮助......我无法为下拉菜单找到相同的工作。能否请你帮忙? stackoverflow.com/questions/48517602/…
    【解决方案2】:

    您正在混合演示视图和表单的值。我认为最好将概念分开。我们可以使用 formObj 来创建表示,并使用 callbackForm 来创建值。查看代码中的cmets

    //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;
      }
    

    我们有一个 callbackForm 方式为 "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 分开是一个有趣的概念。我也会试试这个。
    猜你喜欢
    • 2018-07-09
    • 2019-03-26
    • 2023-04-02
    • 2021-06-25
    • 2020-07-11
    • 1970-01-01
    • 2018-03-02
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多