Angular-反应形式的多个单选按钮

时间:2019-01-09 15:31:51

标签: angular angular6 angular-reactive-forms reactive-forms

我们有如下列表(在原始实现中productList将来自API)

productList = [{
    productId: "104",
    productName: "computer"
  },
  {
    productId: "105",
    productName: "Sprots"
  },
  {
    productId: "106",
    productName: "TV"
  }];

我们需要将产品名称显示为html中的单选按钮

[] Computer
[] Sports
[] TV

当我们选择一个单选按钮时,它应该在组件中提供选定的项(例如,如果我们选择“电视”单选按钮,可能是这样的吗?

this.myForm.controls['productMethods'].valueChanges.subscribe(value => {
      var a  = value 
      // how can i get a = { productId: "106",productName: "TV"} **?**
    }

对于预选:-

[] Computer
[x] Sports <== how to make sports as pre-selected on page load also **?**
[] TV

我尝试的是https://stackblitz.com/edit/angular-formarray-example-2-3xq45k,但无法显示单选按钮。

谢谢

3 个答案:

答案 0 :(得分:1)

Here is an updated version of your Stackblitz.

首先,由于您正在使用单选输入,因此您只会接收一个值,而不是数组。

this.productFormGroup = this.formBuilder.group({
  productMethod: new FormControl("105"),
});

第二,您的无线电输入都必须具有相同的名称(该名称必须与formControlName匹配)。

<input type="radio"
  formControlName="productMethod"
  id="radio{{i}}"
  name="productMethod"
  [value]=item>
<label class="custom-control-label"
  for="radio{{i}}">
  {{item.productName || '?'}}
</label>

第三,我不会将对象用作表单值,因为您无法轻松地比较对象以设置默认值。使用productId并使用一种方法来检索相应的产品。

getProductById(id): any {
  return this.productList.find(p => p.productId == id);
}

最后,我进行了其他一些小的更改,以使您的代码更好一些。

<div [formGroup]="productFormGroup">
  <div *ngFor="let item of productList; let i = index;">
    <input type="radio"
      formControlName="productMethod"
      id="radio{{i}}"
      name="productMethod"
      [value]=item.productId>
    <label class="custom-control-label"
      for="radio{{i}}">
      {{item.productName || '?'}}
    </label>
  </div>
</div>
{{ getProductById(productFormGroup.controls.productMethod.value) | json }}

答案 1 :(得分:0)

1。-您需要输入“ formArrayName”

2.-formControlName用[]括起来

3。单选按钮???如果您需要单选按钮,则仅是一个formControlName,而不是一个数组

void main()
{
    int a[] = { 1,2,3 };
    int b[] = { 4,5,6 };
    int array[][3] = { a,b };
}

注意:如果需要单选按钮

<div [formGroup]="productFormGroup">
    <!---you need write "formArrayName"--->
    <div formArrayName="productMethods">
        <div *ngFor="let item of productList; let i = index">
            <div>
                <!--formControlName is enclosed by []-->
                <input type="checkbox" name="{{'acceptable'+i}}" [formControlName]="i">
                <label class="custom-control-label" 
                    for="{{ 'acceptable' + i}}">{{item.productName}}
               </label>
           </div>
        </div>
    </div>
</div>

this.myForm.controls['productMethods'].valueChanges.subscribe(value => {
      //value becomes, e.g. [true,false,false]
      values.forEach((v,index)=>{
         if (v)
           console.log(productList[i]);
      })
    }

但是您的表单就像

<div [formGroup]="productFormGroup">
    <div *ngFor="let item of productList; let i = index" >
        <input type="radio" name="product" formControlName="product" [value]="item" >
    <label class="custom-control-label" 
        for="{{ 'acceptable' + i}}">{{item.productName}}</label>
    {{item.productname}}
  </div>
</div>

答案 2 :(得分:0)

有点晚了,但让我留在这里。 角材具有mat-radio-group,在您的模块import {MatRadiomodule} from '@angular/material'中,也将其导入@NgModule内。

在您的component中。

this.formGroupVariable = this.fb.group({
    productItem: ['', Validators.required],
    . . .
});

然后在您的template component

<mat-radio-group *ngFor="let productItem of productList">
    <label for="{{productItem.value}}" class="radio-inline">
        <input id="{{productItem.value}}" 
               [value]="productItem.value"
               formControlName="productItem"                                          
               type="radio"
               name="requestType"
               [checked]="productItem.value==='Sports'">
               {{productItem.value}}
    </label>
</mat-radio-group>

我希望这会有所帮助。