【问题标题】:How to get selected Radio Button values from Mat-radio-group with For loop in Angular如何在 Angular 中使用 For 循环从 Mat-radio-group 中获取选定的单选按钮值
【发布时间】:2019-10-14 13:31:47
【问题描述】:

我有一个复杂的对象,例如,如下所示

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']}
];

我想从中进行问卷调查,以确保他们对答案的评分为 0-5,现在当我呈现如下所示的 html 时

<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>

这是正确呈现的,但是当我选择我的第一个问题评级为 1 时,它也会从所有其他评级中进行选择,而且我想捕获这些我尝试过的每个评级 [(ngModel)] 但它只给出一个值一个数组

在我的 .ts 文件中,我将模型引用作为 Array 给出,如下所示:

sectionRating: any[] = [];

【问题讨论】:

  • 您可以使用一个布尔属性来选中或取消选中单选按钮
  • 但我需要分别对每个部分进行评级,并且我们可以在 somename 对象中拥有 n 个对象。
  • 可以创建一个stackblitz吗?

标签: angular angular-material angular-template-form


【解决方案1】:

你可以试试这个,使用(change)事件,然后在本地变量中添加点击项。

HTML 代码:

<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 代码:

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

【讨论】:

  • 我从你的 (@prashant) 解决方案中得到了解决,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-01-20
  • 2017-11-23
  • 2019-10-31
  • 1970-01-01
  • 2015-01-08
  • 2020-02-10
  • 2020-12-01
  • 1970-01-01
相关资源
最近更新 更多