Angular 2:单选按钮无法正常工作

时间:2017-08-13 16:42:08

标签: angular twitter-bootstrap-3

我通过迭代购物车中的商品来创建表格。对于每个项目,我创建一个单选按钮的交付方法列,允许用户选择三种交付方式之一(STORE PICKUP,TRUCK DELIVERY,PARCEL)。

创建表行,每行有三个可以选择的不同单选按钮。问题是当在一行中选择一个单选按钮时,“STORE PICKUP”,例如,为表格中的每一行选择所有“STORE PICKUP”单选按钮。我希望只选择我选择的特定行的收音机“STORE PICKUP”。我做错了什么?

<tr *ngFor="let item of cartService.cart.items">
      <td class="lgcol">
        <a [routerLink]="['/product', item.product._id]">
            <img src="..\assets\image\{{getDisplayImage(item.product, item.color)}}" >
            <br/><br/>
            <p>{{item.product.name}}</p>
          </a>
        <p>Item #{{item.product.model}}</p>
      </td>
      <td class="lgcol">
        <p *ngFor="let delivery of dataService.deliveryMethods">
            <input type="radio" name="deliveryMethod" [(ngModel)]="item.deliveryMethod"
              [value]="delivery.value">
            {{delivery.label}}
          </p>
        <br>
      </td>
</tr>

购物车项目类:

export class CartItem {
  product: Product;
  quantity: number;
  itemTotal: number;
  color: string;
  protectionPlan: string;
  deliveryMethod: string;
}

提供方法:

deliveryMethods = [
   { value: 'Store Pickup', label: 'Store Pickup' },
   { value: 'Truck Delivery', label: 'Truck Delivery' },
   { value: 'Parcel Shipping', label: 'Parcel Shipping' },    
 ]

1 个答案:

答案 0 :(得分:3)

您应为name的单选按钮组分配不同的cart.item属性。由于您的所有电台input都有相同的名称,因此它们被认为是相同的。

要解决此问题,您可以将属性名称与cart.items

name="deliveryMethod{{i}}"索引连接起来
<tr *ngFor="let item of cartService.cart.items;let i=index;">
    <td class="lgcol">
        <a [routerLink]="['/product', item.product._id]">
          <img src="..\assets\image\{{getDisplayImage(item.product, item.color)}}" >
          <br/><br/>
          <p>{{item.product.name}}</p>
        </a>
        <p>Item #{{item.product.model}}</p>
    </td>
    <td class="lgcol">
        <p *ngFor="let delivery of dataService.deliveryMethods">
            <input type="radio" name="deliveryMethod{{i}}" 
              [(ngModel)]="item.deliveryMethod" [value]="delivery.value" /> 
            {{delivery.label}}
        </p>
        <br>
    </td>
</tr>
相关问题