RadioButton ngmodel not working for boolean values

Issue

I have two radio buttons in Sample with ngModel.

<div id="container">
    <input type="radio" id="radiobuttonstoerung1" label="Blinkend" name="stoerungBlinkend" [(ngModel)]="project.modelvalue"
          value="true"/>
    <input type="radio" id="radiobuttonstoerung2"  label="Dauersignal" name="stoerungBlinkend" [(ngModel)]="project.modelvalue"
  value="false"/>
</div>

When I passed the boolean variable it is not working.

export class RadioButtonController implements OnInit {
    project = { modelvalue: true };
}

Sample Link: https://stackblitz.com/edit/angular-cxt8bs-quvb7y?file=radiobutton.html

Scenario when I passed ‘stoerungBlinkend’ as true, RadioButton with value=”true” should be checked. If I passed it as false, then RadioButton with value =”false” should be checked.

I have found the workaround solution, but could anybody explain in detail why the above scenario is not working?

Solution

As explained in the Angular documentation, when you set the radio button value with value="true", you actually set the value to the string "true", which is not identical to the boolean true.

To set a boolean value on the input element, use property binding with [value]="true":

<input type="radio" ... [(ngModel)]="project.stoerungBlinkend" [value]="true" />    
<input type="radio" ... [(ngModel)]="project.stoerungBlinkend" [value]="false" />

See this stackblitz for a demo.

Answered By – ConnorsFan

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.