【问题标题】:how to loop through array using ngFor in angular 11如何在角度 11 中使用 ngFor 循环遍历数组
【发布时间】:2021-04-27 11:43:05
【问题描述】:

我有一个类似的 api 响应

res.attribute

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

我需要两组用于大小和颜色的单选按钮。我通过它实现了这一点

 <section class="example-section"  *ngFor="let attr of Attr" >
      
        <mat-radio-button *ngFor="let checkbox of attr.items.split(',')" class="example-margin">{{checkbox}}</mat-radio-button>
    
    </section>

但是,每个单选按钮的名称都一样(只能从所有 4 个(s、m、l、yellow)中选择一个)

我期待的是两组不同的单选按钮,例如大小和颜色

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    您可以将输入属性name 与您想要的收音机类型绑定。

    [name]="attr.attr_slug"
    

    这样它就有了一个广播组,该组将按您的 slug 名称进行分组。

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

    【讨论】:

    • 我需要这两个选定的值...这怎么可能?
    【解决方案2】:

    您应该使用mat-radio-group 将内部的单选按钮分组。尝试如下:

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

    编辑: 要获得所需的“s,yellow”或“m,yellow”输出,您可以执行以下解决方法。

    因为你的蛞蝓是大小和颜色。定义一个模型在你的组件中有这些属性:

    model = {
    size = "",
    color = "",
    }
    

    将无线电组绑定到相应的属性,如下所示

    <mat-radio-group [name]="attr.attr_slug" [value]="model[attr.attr_slug]">
    

    所以稍后在您的组件中获取您的组合值,如下所示:

    const finalValue = `${this.model.size}, ${this.model.color}`
    

    【讨论】:

    • 如何从中获取选定的值?
    • @Pugazh 广播组有一个名为 value 的属性,它为您提供选定的值。
    • 谢谢,但我需要像“s,yellow”或“m,yellow”这样的值(参考 api 响应)
    • 我尝试使用 (click)="onClick(checkbox)" ,我最近点击了按钮..但我需要一对大小和颜色
    • 对不起@Eldar ..我什么也没得到...我提出了一个详细的问题..请查看stackoverflow.com/questions/67294497/…
    【解决方案3】:

    正如@Eldar 所说,您需要在mat-radio-group 中包含mat-radio-button,那么您就有两组不同的单选按钮组。您可以参考 Angular Material 文档here

    【讨论】:

    • 如何从中获取选定的值
    猜你喜欢
    • 1970-01-01
    • 2016-11-02
    • 2019-03-21
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多