如何从 angular 11 中的单选按钮获取值

how to get value from radio button in angular 11

我有一个 API 回复,

0: {relate_id: 15, pid: 9, attr_slug: "size", items: "s,m,l", id: 1, …}
1: {relate_id: 16, pid: 9, attr_slug: "color", items: "yellow", id: 2, …}
length: 2

这是产品的品种详细信息..0:尺寸..和 1:is 颜色(可能会有所不同,如公斤、公羊等..)

我有这样的单选按钮,

 <section class="example-section"  *ngFor="let attr of Attr" >
      
        <mat-radio-button *ngFor="let checkbox of attr.items.split(',')" 
         [name]="attr.attr_slug"  (click)="onClick(checkbox)" [value]="model[attr.attr_slug]" 
          class="example-margin">{{checkbox}}</mat-radio-button>
    
    </section>

这个 onclick 只是给出最近点击的...但我需要一对 1: & 2: 比如 ("s,yellow) or ("m,yellow),..

我也尝试过 [value] 和模型

model:any = {
  size : "",
  color : "",
  }
  finalValue = `${this.model.size}, ${this.model.color}`

但我在 console.log(this.finalvalue) 中只得到 ','...如何实现?

您必须使用 mat-radio-group 并使用 change 输出来检测更改:

<section *ngFor="let attr of Attr" >
  <mat-radio-group [value]="model[attr.attr_slug]"
                   [name]="attr.attr_slug"
                   (change)="onRadioChange()">
    <mat-radio-button *ngFor="let checkbox of attr.items.split(',')" 
                      [value]="checkbox">
      {{checkbox}}
    </mat-radio-button>
  </mat-radio-group>
</section>
@ViewChildren(MatRadioGroup)
radios?: QueryList<MatRadioGroup>;

onRadioChange(): void {
  const value = this.radios?.map((radio) => radio.value).join(','); 
}