Here is my code, In last name i used ngModel so its working two way data binding but in radio button how I used ngModel for two way data binding.
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !lastname.valid }">
<label for="lastname">Last Name</label>
<input type="text" class="form-control" name="last_name" [(ngModel)]="employee.last_name" #lastname="ngModel" required />
<div *ngIf="f.submitted && !lastname.valid" class="help-block">Last Name is required</div>
</div>
<div class="form-group">
<label>Gender:</label>
<label class="radio-inline">
<input type="radio" name="optradio" [checked]="employee.gender == 'Male'" >Male
</label>
<label class="radio-inline">
<input type="radio" name="optradio" [checked]="employee.gender == 'Female'" >Female
</label>
</div>
Adding two-way data bindinglink Angular's two-way binding syntax is a combination of square brackets and parentheses, [()] . The [()] syntax combines the brackets of property binding, [] , with the parentheses of event binding, () , as follows.
One-way and two-way data binding are two of the important ways by which we can exchange data from component to DOM and vice-versa. Data exchange between the component and the view will help us to build dynamic and interactive web applications.
Two-way data binding refers to sharing data between a component class and its template. If you change data in one place, it will automatically reflate at the other end. For example, if you change the value of the input box, then it will also update the value of the attached property in a component class.
In order to achieve a two-way binding, we will use ngModel or banana in a box syntax. To make sure the app doesn't break, we need to import 'FormsModule' from '@angular/forms. Any changes to the view are propagated to the component class.
For two way data binding its as same as all others use this syntax [(ngModel)]
Replace your code block with below:
<div class="form-group">
<label>Gender:</label>
<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>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With