How correctly bind data to radio buttons in Angular2?

Seva picture Seva · Mar 29, 2017 · Viewed 42.7k times · Source

I have a component with two radio buttons, HTML looks like :

<div class="btn-group"  id="ProfitCodes">
<div class="radio">
    <label>
        <input type="radio"
           class="radio-inline"
           value="1"
           [checked]="model.ForeignCompany.ProfitCode === 1"
           [(ngModel)]="model.ForeignCompany.ProfitCode"
           id="point1"
           name="ProfitCode"><small>description</small>
    </label>
</div>
<div class="radio">
    <label>
        <input type="radio"
           class="radio-inline"
           [(ngModel)]="model.ForeignCompany.ProfitCode"
           [checked]="model.ForeignCompany.ProfitCode === 2"
           value="2"
           id="point2"
           name="ProfitCode"><small>description</small>
    </label>
</div>

When I click save and send model to server I see valid selected value of radio button on server side. And this value stored in the database without errors. But radio button with appropriate value is not checked after binding data. In devTools I see the first radio button:

<input class="radio-inline ng-untouched ng-pristine ng-valid" id="point1" name="ProfitCode" title="asdasda" type="radio" value="1" ng-reflect-name="ProfitCode" ng-reflect-value="1" ng-reflect-model="2" ng-reflect-checked="false">

Second radio button:

<input class="radio-inline ng-untouched ng-pristine ng-valid" id="point2" name="ProfitCode" title="asd" type="radio" value="2" ng-reflect-name="ProfitCode" ng-reflect-value="2" ng-reflect-model="2" ng-reflect-checked="true">

I see that angular changed attributes and waiting that second radio button will be checked. But this does not happen. What am I doing wrong?

Answer

Seva picture Seva · Mar 30, 2017

This works in my case. I removed [(ngModel)]

<div class="radio">
<label>
    <input type="radio"
           value="1"
           [checked]="model.ForeignCompany.ProfitCode === 1"
           id="point1"
           (change)="onProfitSelectionChange(1)"
           name="ProfitCode"><small>description</small>
</label>
</div>
<div class="radio">
    <label>
        <input type="radio"
               value="2"
               [checked]="model.ForeignCompany.ProfitCode === 2"
               id="point2"
               (change)="onProfitSelectionChange(2)"
               name="ProfitCode"><small>description</small>
    </label>
</div>

and TS method looks like:

onProfitSelectionChange(entry): void {
    this.model.ForeignCompany.ProfitCode = entry;
}