Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 612
vinoth-kumar-s Avatar asked Oct 09 '18 13:10

vinoth-kumar-s


2 Answers

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.

like image 92
ConnorsFan Avatar answered Oct 17 '22 11:10

ConnorsFan


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>
like image 1
Leonel Tasso Guimaraes Avatar answered Oct 17 '22 12:10

Leonel Tasso Guimaraes