Reputation: 5084
I am generating radio buttons in Angular as:
<div class="radio" *ngFor="let gender of genders">
<input type="radio" name="gender" [checked]="gender=='male'" [value]="gender" > {{gender}}
</div>
This works fine, and the radio for "male" is checked by default. The problem is, I have to add the ngModel
directive to have the field added to the form object. When I do, however, the default checked behavior doesn't work and no radio is checked by default.
<input type="radio" name="gender" [checked]="gender=='male'" [value]="gender" ngModel> {{gender}}
Any advice?
Upvotes: 0
Views: 296
Reputation: 73771
As mentioned in the Angular documentation:
The ngModel data property sets the element's value property...
When the ngModel
directive is used, you should set its value to initialize the input element. You can do so with data binding. Here are three possible syntaxes:
<input type="radio" name="gender" [value]="gender" [ngModel]="genders[0]" >
<input type="radio" name="gender" [value]="gender" [ngModel]="'male'" >
<input type="radio" name="gender" [value]="gender" ngModel="male" >
This stackblitz shows these various cases. You can also see an additional example where the ngModel
value is not set. In that case, the radio button with an empty string value is checked by default, even if we try to set the checked
property of a different button.
Upvotes: 1