【问题标题】:how to get value from radio button in angular 11如何从角度 11 中的单选按钮获取值
【发布时间】:2021-07-21 11:19:03
【问题描述】:

我有一个类似的 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:表示颜色(可能会有所不同,如 kg、ram 等)

我有类似的单选按钮,

 <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: like ("s,yellow) or ("m,yellow),..

我也尝试了 [value] 和 model as

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

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

【问题讨论】:

    标签: angular typescript forms data-binding ngfor


    【解决方案1】:

    您必须使用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(','); 
    }
    

    【讨论】:

    • 谢谢..但我需要一对像“s,yellow”或“m,yellow”这样的值(参考API响应)
    • @radio === change.source ...(error) 由于“MatRadioGroup”和“_MatRadioButtonBase”类型没有重叠,此条件将始终返回“false”。
    • 属性 'radios' 没有初始化器,也没有在 constructor.ts(2564) 中明确赋值
    • @barathkumar 现在怎么样?
    • @barathkumar 你可以在这里发表评论并附上链接:)
    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多