user1400915
user1400915

Reputation: 1943

Angular 2 Radio Button 2 way Binding

I have 3 radio buttons as follows:

.html:

<input type="radio" name = "options" value="All" [checked]='selectedRadioButtonValue' (input)='selectedRadioButtonValue=$event.target.value' />
<span class="radioClass">{{"All("+all+")"}}</span>

<input type="radio" name = "options" value="Male" [checked]='selectedRadioButtonValue' (input)='selectedRadioButtonValue=$event.target.value' />
<span class="radioClass">{{"Male("+male+")"}}</span>

<input type="radio" name = "options" value="Female" [checked]='selectedRadioButtonValue' (input)='selectedRadioButtonValue=$event.target.value' />
<span class="radioClass">{{"Female("+female+")"}}</span>

I dont want to use [(ngModel)] because of package issues .

I want to use [] and () traditional ways .

Now, the thing is values are not getting changed in the selectedRadioButtonValue . Whats the issue here?

export class EmployeeComponent {

selectedRadioButtonValue: string = "All";

}

Upvotes: 2

Views: 7872

Answers (2)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37373

without ngModel Demo :

using change event binding and the value of checked attribute must be a boolean not a string because strings are truthy :

<input type="radio" name = "options" value="All" [checked]="selectedRadioButtonValue === 'All'" (change)='selectedRadioButtonValue=$event.target.value' />
<span class="radioClass">{{"All("+all+")"}}</span>

<input type="radio" name = "options" value="Male" [checked]="selectedRadioButtonValue === 'Male' " (change)='selectedRadioButtonValue=$event.target.value' />
<span class="radioClass">{{"Male("+male+")"}}</span>

<input type="radio" name = "options" value="Female" [checked]="selectedRadioButtonValue === 'Female'" (change)='selectedRadioButtonValue=$event.target.value' />
<span class="radioClass">{{"Female("+female+")"}}</span>

Upvotes: 4

shivlal kumavat
shivlal kumavat

Reputation: 888

For two way data binding its as same as all others use this syntax [(ngModel)]

<div class="form-group">
<label>Gender:</label> 
&nbsp;

<label class="radio-inline">
    <input type="radio" name="optradio" value='Male' [(ngModel)]="employee.gender" >Male
</label>

<label class="radio-inline">
    <input type="radio" name="optradio" value='Female' [(ngModel)]="employee.gender" >Female
</label>

Upvotes: 5

Related Questions