vinoth-kumar-s
vinoth-kumar-s

Reputation: 85

RadioButton ngmodel not working for boolean values

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?

Upvotes: 6

Views: 10969

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73731

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.

Upvotes: 17

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>

Upvotes: 0

Related Questions