简体   繁体   中英

mdl-radio with ngFor each radio button that is clicked remains selected

I have three product arrays and a variable to hold current one as a selection:

product_types=['One', 'Two', 'Three']

product_type_one = [
{'description': 'Type one sample one', 'type': 'one'},
{'description': 'Type one sample two', 'type': 'one'},
{'description': 'Type one sample three', 'type': 'one'},
] 

product_type_two = [
{'description': 'Type two sample one', 'type': 'two'},
{'description': 'Type two sample two', 'type': 'two'},
{'description': 'Type two sample three', 'type': 'two'},
] 

product_type_three = [
{'description': 'Type three sample one', 'type': 'three'},
{'description': 'Type three sample two', 'type': 'three'},
{'description': 'Type three sample three', 'type': 'three'},
] 

selectedProduct=null;

On my template I am populating radio buttons so that user can select one of the product groups as following:

  <div class="my-filters" *ngFor="let product of product_types">
    <mdl-radio 
    name="productgroup" 
    value="product" 
    ngModel='selectedProduct'
    (change)="showProduct(product)"
    mdl-ripple>{{product}}</mdl-radio>
  </div><br>


 <mdl-card *ngFor="let product of selectedProduct" class="demo-card-event" mdl-shadow="2">
  <mdl-card-title mdl-card-expand>
   <h4>
     {{product.description}}
   </h4>
 </mdl-card-title>
 <mdl-card-actions mdl-card-border>
  <button mdl-button mdl-colored mdl-ripple (click)="openDialog()">
    view
  </button>
  <mdl-layout-spacer></mdl-layout-spacer>
  <mdl-icon>shopping_cart</mdl-icon>
</mdl-card-actions>
</mdl-card>

Until here whatever radio button user clicks, correct array is populated in my mdl-cards, however all the radio buttons that user clicks one after other remain clicked and not just the current selection:

在此处输入图片说明

What am I doing wrong?

You should be grouping them using md-radio-group as below,

<md-radio-group class="productgroup" [(ngModel)]="selectedProduct">
   <mdl-radio  *ngFor="let product of product_types"
       value="product" 
      (change)="showProduct(product)"
      mdl-ripple>{{product}}</mdl-radio>
</md-radio-group>

I updated my for loop like following:

 <div *ngFor="let product of product_types" class="my-filters">
    <mdl-radio name="productgroup" [value]='product' [(ngModel)]="selectedProduct" (change)="showProduct(product)"> {{product}} </mdl-radio> <br>
  </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM