.Html Changes
<div class="container">
<div class="row">
<div class="form-bg">
<form #studentForm="ngForm" (ngSubmit)="RegisterStudent(studentForm)">
<div class="form-group">
<label>Gender</label>
<div class="form-control">
<label class="radio-inline">
<input type="radio" name="gender" value="male" ngModel>
Male
</label>
<label class="radio-inline">
<input type="radio" name="gender" value="female" ngModel>
Female
</label>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
Here, in the above html code, we can see the name attribute is having a common value
as gender. The most important point that you need to keep in mind is that both the radio buttons should have the same value for the “name” attribute. Otherwise the radio button selection won’t be mutually exclusive
Again if you notice we have set the value attribute of each radio button to male and female and this is the value which is going to be posted to the server when the form is submitted.
.ts Changes
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-formsvalidation',
templateUrl: './formsvalidation.component.html',
styleUrls: ['./formsvalidation.component.css']
})
export class FormsvalidationComponent {
RegisterStudent(studentForm: NgForm): void {
console.log(studentForm.value);
}
}
Output
Radio Button Default Checked.
Note:
With the above changes now browse the application and you will see the Male radio button is not checked.
if you remove the “ngModel” directive from the radio button , then it is checked by default.
<input type="radio" name="gender" value="male" checked>
we generally use the “ngModel” directive for two-way data binding. So when we put the ngModel directive back into the control then the “checked” attribute will not work as expected.
We can make it work as below
.ts changes
@Component({
selector: 'app-formsvalidation',
templateUrl: './formsvalidation.component.html',
styleUrls: ['./formsvalidation.component.css']
})
export class FormsvalidationComponent {
gender = 'male';
RegisterStudent(studentForm: NgForm): void {
console.log(studentForm.value);
}
}
<div class="form-control">
<label class="radio-inline">
<input type="radio" name="gender" value="male" [(ngModel)]="gender">
Male
</label>
<label class="radio-inline">
<input type="radio" name="gender" value="female" [(ngModel)]="gender">
Female
</label>
</div>
No comments:
Post a Comment
Thank you for visiting my blog