1

I'm trying to create a list of radio buttons from categories. The categories is an array of objects like this:

[ { _id: '58cfb65b2ad6426beec93231' label: 'Category name', checked: true }, { _id: '58cfb65b2ad6426beec93232' label: 'Category name 2', checked: false } ] 

Now I try to render a list of radio buttons and want to set checked by the checked value.

<label *ngFor="let cat of categories"> <input type="radio" name="category" [checked]="cat.checked" [(ngModel)]="selectedCategory" [value]="cat._id"/> {{ cat.label[lang.code] }} </label> 

The radio buttons all come up unchecked and selectedCategory is undefined. When I submit the form and check the values it also comes out undefined... Anyone knows what im doing wrong?

0

1 Answer 1

1

Since you are using [(ngModel)], you are telling Angular to do two-way databinding.

Two-way means from code to markup and vice versa. So, when Angular creates the radiobuttons (markup), it will check whether your AppComponent has a selectedCategory property and, if so, it will set the checked attribute on the one radiobutton whose value matches.

This behaviour will -in some way- conflict with setting the [checked] attribute: even if it is set on a radiobutton at creation, it will be reset as soon as the ngModel databinding gets in the way.

Possible solution

In your AppComponent class, double check that the selectedCategory member exists. Then, set the selectedCategory property to the value of the selected category.

E.g., do something like this when you create (or receive) the categories:

for (let c of categories){ if(c.checked){ this.selectedValue = c._id; break; } } 

And, remove the [checked] binding from your markup. This sould suffice:

<label *ngFor="let cat of categories"> <input type="radio" name="category" [(ngModel)]="selectedCategory" [value]="cat._id"/> {{ cat.label[lang.code] }} </label> 
Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense.. Thanks for you help Paolo!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.