How to get selected Radio Button values from Mat-radio-group with For loop in Angular

kishore picture kishore · Oct 12, 2019 · Viewed 14.6k times · Source

I have a complex object i.e., like below

someName = [
{name: "John",id: "1",rating: ['0', '1', '2', '3', '4', '5']},
{name: "robert", id: "2", rating: ['0', '1', '2', '3', '4', '5']},
{name: "luv", id: "3", rating: ['0', '1', '2', '3', '4', '5']}
];

from which I want to make a questionnaire to make sure they rate their answer from 0-5, now when I'm rendering my html like below

<ng-container *ngFor="let sort of someName; let i=index">
   <label id="example-radio-group-label">Rate your favorite section</label>
   <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group" [(ngModel)]="sectionRating">
      <mat-radio-button class="example-radio-button" *ngFor="let section of sort.sections" [value]="section">{{season}}</mat-radio-button>
   </mat-radio-group>
</ng-container>

This is rendering properly but when I select my first question rating as 1 it is also selecting from all other rating also, and also i want to capture these each rating for that i tried [(ngModel)] but its giving only one value instead of an array

in my .ts file, I gave my model reference as Array like this:

sectionRating: any[] = [];

Answer

Prashant Pimpale picture Prashant Pimpale · Oct 12, 2019

You can try this, use (change) event and then add the click item in the local variable.

HTML Code:

<ng-container *ngFor="let sort of someName; let i=index">
    <label id="example-radio-group-label">Rate your favorite section</label>
    <br>
    {{sort.name}}
    <br>
    <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group">
        <mat-radio-button class="example-radio-button" *ngFor="let section of sort.rating" [value]="section"
            (change)="radioChange($event,sort)">
            {{section}}</mat-radio-button>
    </mat-radio-group>
    <br>
    <br>

</ng-container>

<h2>Selected Array</h2>
<div>
   {{finalArray | json }}
</div>

TS Code:

import { Component } from '@angular/core';
import { MatRadioChange } from '@angular/material';
// ...

/**
 * @title Basic radios
 */
@Component({
  selector: 'radio-overview-example',
  templateUrl: 'radio-overview-example.html',
  styleUrls: ['radio-overview-example.css'],
})
export class RadioOverviewExample {
  someName = [
    { name: "John", id: "1", rating: ['0', '1', '2', '3', '4', '5'] },
    { name: "robert", id: "2", rating: ['0', '1', '2', '3', '4', '5'] },
    { name: "luv", id: "3", rating: ['0', '1', '2', '3', '4', '5'] }
  ];

  finalArray: any[] = [];

  radioChange(event: MatRadioChange, data) {
    var obj = this.someName.filter(x => x.id == data.id)[0];
    obj.selected = event.value;
    if (!this.finalArray.some(x => x.id == data.id)) {
      this.finalArray.push(obj);
    }
  }
}

StackBlitz_Demo