I'm trying to build a Angular 2 ponent which displays a list of options with radios. It works fine but it the answer
field of the ponent, which is bound inside [(ng-model)]="answer"
, won't update when selecting one of the options. Am I doing something wrong or isn't this the way to create a list of radio selection options?
<div>
Answer: {{ answer }}
</div>
<div class="radio" *ng-for="#option of itemData">
<label>
<input type="radio" [value]="option.id" [(ng-model)]="answer"
(change)="responseChanged()" name="radio-list">
<span>{{ option.name }}</span>
</label>
</div>
Plunker
I'm trying to build a Angular 2 ponent which displays a list of options with radios. It works fine but it the answer
field of the ponent, which is bound inside [(ng-model)]="answer"
, won't update when selecting one of the options. Am I doing something wrong or isn't this the way to create a list of radio selection options?
<div>
Answer: {{ answer }}
</div>
<div class="radio" *ng-for="#option of itemData">
<label>
<input type="radio" [value]="option.id" [(ng-model)]="answer"
(change)="responseChanged()" name="radio-list">
<span>{{ option.name }}</span>
</label>
</div>
Plunker
Share Improve this question edited Mar 31, 2021 at 8:09 Syscall 19.8k10 gold badges43 silver badges58 bronze badges asked Oct 27, 2015 at 13:00 lucassplucassp 4,1673 gold badges28 silver badges36 bronze badges 1- 1 Here's a custom implementation for radio, don't know about lists though. – Eric Martinez Commented Oct 27, 2015 at 20:50
2 Answers
Reset to default 6Well i guess two way binding is now working with radio, so currently you cannot use [(ng-model)]
.
The alternative is to use the change event and checked attribute. See my plunker
https://plnkr.co/edit/7Zm3qgoSv22Y9KrBn4tS?p=preview
(change)="answer=$event.target.value"
and
[checked]='answer==option.id'
You cannot use ng-model with radio boxes like in angular1. However there are several ponents on github that allows you to do it easily, like ng2-radio-group ponent. It has support for both radio select and multiple checkboxes select:
<radio-group [(ngModel)]="sortBy">
<input type="radio" value="rating"> Rating<br/>
<input type="radio" value="date"> Date<br/>
<input type="radio" value="watches"> Watch count<br/>
<input type="radio" value="ments"> Comment count<br/>
</radio-group>
<checkbox-group [(ngModel)]="orderBy">
<input type="checkbox" value="rating"> Rating<br/>
<input type="checkbox" value="date"> Date<br/>
<input type="checkbox" value="watches"> Watch count<br/>
<input type="checkbox" value="ments"> Comment count<br/>
</checkbox-group>