Angular 2: how to create radio buttons from enum and add two-way binding?
Ok finally I found out the solution. I am currenly using Angular 2 RC5.
The enum value I want to bind my radio is the property:
intervention.rapport.motifIntervention : MotifInterventions
In my @Component I declared private members to give access to enum definition in the html template:
export class InterventionDetails{ private MotifIntervention = MotifIntervention; private MotifInterventionValues = Object.values(MotifIntervention).filter( e => typeof( e ) == "number" ); // model object: private intervention: Intervention;
Here is HTML code for the radio buttons:
<div *ngFor="let choice of MotifInterventionValues"> <input type="radio" [(ngModel)]="intervention.rapport.motifIntervention" [checked]="intervention.rapport.motifIntervention==choice" [value]="choice" /> {{MotifIntervention[choice]}}<br></div>
[(ngModel)]="intervention.rapport.motifIntervention"
is two-waybinding, it is required to update the property in the model (in mycaseintervention.rapport.motifIntervention
)[checked]="intervention.rapport.motifIntervention==choice"
isrequired to update the radio buttons component if the valueintervention.rapport.motifIntervention is modified externally.[value]="choice"
is the value that is assigned to my property whenthe radio button is selected.{{MotifIntervention[choice]}}
is the label of the radio button
A bit late to the party, but this worked for me:
<tr *ngFor="let Item of Items; let idx = index" style="line-height: 10px;"> <td style="font-size:11px;padding-right: 10px;">{{ GetOption(Item) }}</td> <td><input type="radio" [attr.name]="ComponentID" [id]="ComponentID" [value]="GetValue(Item)" [checked]="value == GetValue(Item)" (change)="SelectionChange(GetValue(Item))"></td> </tr>
Where:
- Items is an array of options
- ComponentID is the name of the component
- GetOption is a function that returns the caption that the optionshould use
- GetValue is a function that returns the value that theoption should use
- SelectionChanged is used to update the model
Note that I don't use [(ngModel)]