Pugazh
Pugazh

Reputation: 13

how to loop through array using ngFor in angular 11

i have a api responce like

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

i need two set of radio buttons for size and color..i achived that through

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

but, every radio button is like same name(only one from all 4 (s,m,l,yellow) can be selected)

what i am expecting is two different set of radio buttons like size and color

Upvotes: 0

Views: 331

Answers (3)

Eldar
Eldar

Reputation: 10790

You should be using a mat-radio-group to group up the radio buttons inside. Try it like below :

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

Edit: For getting the desired "s,yellow" or "m,yellow" output you can do a workaround below.

Since your slugs are size and color. Define a model has those properties in your component:

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

Bind the radio group to the corresponding properties like below

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

So later in your component get your combined value like this :

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

Upvotes: 1

Qayyum Shareef
Qayyum Shareef

Reputation: 44

As @Eldar said you need to include mat-radio-button inside mat-radio-group then you have two different sets of radio button groups. You can refer to the Angular Material docs here.

Upvotes: 0

Abhinav Kumar
Abhinav Kumar

Reputation: 3036

You can bind the input property name with the radio type you want.

[name]="attr.attr_slug"

This way it has a radio group that will be group by your slug name.

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

Upvotes: 1

Related Questions