RadioButton ngmodel not working for boolean values
Asked Answered
P

2

6

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?

Progressionist answered 9/10, 2018 at 13:43 Comment(1)
What is the behavior that you expected? And what is the actual result? Please describe preciselyMinicam
W
17

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.

Warms answered 9/10, 2018 at 14:8 Comment(0)
S
0

Try something like this:

Your TS:

    form: FormGroup;
constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
            gender: ['', Validators.required]
});
}

HTML:

<form [formGroup]="form">
    <input type="radio" value='Male' formControlName="gender" >Male
    <input type="radio" value='Female' formControlName="gender">Female
</form>
Sasin answered 9/10, 2018 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.