Search code examples
angulartypescriptdata-binding

Angular 7: Checkbox of type radio, use ngModel or change-function?


<label>Yes</label>
<input type="radio" name="dia?" [checked]="info.bDia" (change)="onchangeDia(dia?.checked)">&nbsp;
<label>No</label>&nbsp;
<input type="radio" name="dia?" [checked]="!info.bDia" (change)="onSaveDiabetes(dia?.checked)" />

I have an input of type of radio and two checkboxes. I wonder how to get the current value, because I need to change a variable.

onchangeDia(val: boolean){
    this.info.bDia = val; // if I log both I get null
}

So, I have no clue how to do it. The problem is that jus one checkbox can be checked - I need to check which one. If the checkbox with the label "Yes" info.bDia chould change to true. I would do it with Two-Way-Data-Binding but it does not work for me neither.


Solution

  • You don't need to add any function on change. Only adding [(ngModel)] will work.

    Try like this:

    <label>Yes</label>
    <input type="radio" name="dia" [value]="true" [(ngModel)]="info.bDia">&nbsp;
    
    <label>No</label>&nbsp;
    <input type="radio" name="dia"  [value]="false"  [(ngModel)]="info.bDia"/>
    

    Working Demo