How to bind data to switches in Angular2?

I have a component with two HTML look like radio buttons

 <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> </div> 

When I click the "Save and send model to server" button, I see the actual selected value of the switch on the server side. And this value is stored in the database without errors. But the radio object with the corresponding value is not read after data binding. In devTools, I see the first switch:

 <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 switch:

 <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 is changing the attributes and is expecting the second switch to be checked. But this does not happen. What am I doing wrong?

+7
radio-button angular data-binding
source share
2 answers

This works in my case. I am removing [(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> </div> 

and the TS method is as follows:

 onProfitSelectionChange(entry): void { this.model.ForeignCompany.ProfitCode = entry; } 
+14
source share

You do not need to [mark] try using [(ngModel)] also use [value] = "1" instead of value = "1"

 <input type="radio" name="Coverage" [value]="1" [(ngModel)]="formdata.coverage_verified" />Yes 
+1
source share

All Articles