angularradio-buttontwo-way-binding

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


I'm trying to use Angular2 syntax to create radio buttons from an enum definition, and bind the value to a property that has the type of that enum.

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 the set of choices and values:

private motifChoices: any[] = [];

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

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 seek to bind the value selected to a property. But when I click one of the buttons the value choice.value is set to undefined.


Solution

  • 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>