Angular 2: how to create radio buttons from an enumeration and add two-way binding?

I am trying to use Angular2 syntax to create switches from an enumeration definition and bind a value to a property that has the type of this enumeration.

My html contains:

<div class="from_elem"> <label>Motif</label><br> <div *ngFor="let choice of motifChoices"> <input type="radio" name="motif" [(ngModel)]="choice.value"/>{{choice.motif}}<br> </div> </div> 

In my @Component, I declared a set of options and values:

 private motifChoices: any[] = []; 

And in the constructor of my @Component, I filled in the following options:

 constructor( private interService: InterventionService ) { this.motifChoices = Object.keys(MotifIntervention).filter( key => isNaN( Number( key ))) .map( key => { return { motif: key, value: false } }); } 

The radio buttons are displayed correctly, now I'm trying to bind the value selected to the property. But when I click one of the buttons, the value.value is undefined.

+6
angular button binding radio two-way
Sep 08 '16 at 13:12
source share
1 answer

Ok, finally I found a solution. I am using Angular 2 RC5.

The enum value that I want to associate with my radio is a property:

intervention.rapport.motifIntervention : MotifInterventions

In my @Component, I declared that private members provide access to the 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 the 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 a two-way binding, you need to update the property in the model (in my case intervention.rapport.motifIntervention )

  • [checked]="intervention.rapport.motifIntervention==choice" switch component must be updated if the value of the Intervention .rapport.motifInterface is changed externally.

  • [value]="choice" is the value assigned to my property when the switch is selected.

  • {{MotifIntervention[choice]}} is the switch label

+11
Sep 08 '16 at 16:57
source share



All Articles