我有一个复杂的对象,例如下面的
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']}
];
现在我要像下面这样呈现html时,我想从中进行问卷调查以确保他们对答案的评分为0-5。
<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[] = [];
答案 0 :(得分:2)
您可以尝试使用(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);
}
}
}