Reputation: 343
I have created a group of radio-buttons. I want to set a default radio button 'checked' and whenever dynamically the other radio buttons are clicked how can i capture which radio button.so,that i can use accordingly in my conditional statements in my typescript."CHECKED" Tag will not work
<form [formGroup]="Form">
<div class="bx--row">
<fieldset class="bx--fieldset">
<legend class="bx--label">HEYHELLOWORLD</legend>
<div class="bx--form-item">
<div class="bx--radio-button-group ">
<input id="radio-button-1" class="bx--radio-button" type="radio" formControlName="selectedOption"
value="0" checked>
<label for="radio-button-1" class="bx--radio-button__label">
<span class="bx--radio-button__appearance"></span>
HEY<br>
</label>
<input id="radio-button-2" class="bx--radio-button" type="radio" formControlName="selectedOption"
value="1" tabindex="0">
<label for="radio-button-2" class="bx--radio-button__label">
<span class="bx--radio-button__appearance"></span>
HELLO<br>
</label>
<input id="radio-button-3" class="bx--radio-button" type="radio" formControlName="selectedOption"
value="2" tabindex="0">
<label for="radio-button-3" class="bx--radio-button__label">
<span class="bx--radio-button__appearance"></span>
WORLD
</label>
</div>
</div>
</fieldset>
</div>
</form>
Above is my HTML part with reactive form TS:
heyForm() {
this.Form = this.formBuilder.group({
selectedOption: ["", Validators.required],
});
}
How will i get the value selected in TS file so that i can use which radio button is clicked in my conditional statement?
Upvotes: 1
Views: 652
Reputation: 12970
Initilize the form control with the value of whatever radio button you want to be checked as default. There is no need of adding a default checked
attribute in the any of the radio buttons
this.form = this._fb.group({
selectedOption: ["1", Validators.required], // this will make the second radio button checked as default.
});
If you want to access which radio button was clicked, you can do it through:
this.form.get('selectedOption').value
Have a function fetching the above value on (change)
event over the radio buttons.
For example:
<input (change)="foo()" id="radio-button-1" class="bx--radio-button" type="radio" formControlName="selectedOption" value="0">
// inside the method foo() check for the currently selected radio button
See an example here: https://stackblitz.com/edit/angular-kw8bhf
Upvotes: 2