Search code examples
angularangular-ngmodel

Creating radio buttons with NgFor


I want to use NgFor to create a set of radio buttons as part of a form. They appear just fine but as soon as I get NgModel involved it breaks so that clicking any of them always selects the last one (except the last which selects the second-to-last).

I have set up a plunk of the issue

Everything seems to work fine if you remove the ngModel from the end of line 12 in the template but without that my form is dead in the water. Right?

Any advice would be great. I'm a proper newb to forms and a relative newb to NgModel.

Cheers


Solution

  • Remove the attr part when binding to your input.

    From this :

     <input type="radio" name="gameType" [attr.id]="'gameType'+i" [attr.value]="i" ngModel>
    

    To this :

     <input type="radio" name="gameType" [id]="i" [value]="i" ngModel>
    

    Here's the modified plunker