I have a dynamically created radio group inside a table in my component. I am using a ngFor to create the radio buttons. And there's a clear button outside the ngFor. I want to clear the radio group when the clear button is clicked. Below is what I am doing right now, but it only works partially. for example, if I have three radio buttons I can only clear if I select the first one and unable to clear the radio group if I select 2nd or 3rd radio. so can anyone tell me what I am doing incorrectly here or suggest a better way of doing it for my scenario. thank you
html:
<table>
<tr *ngFor="let member of members; let i = index">
<td>
<div class="radio-primary">
<input type="radio" #qwerty id="selectId{{i}}">
</td>
</tr>
</table>
<a (click)="clear()" [innerHTML]="clear"></a>
ts file :
@ViewChild('qwerty') qwerty: ElementRef;
clear(): void {
this.qwerty.nativeElement.checked = false;
}
You need to modify some following changes in your structure.
<table>
<tr *ngFor="let member of members; let i = index">
<td>
<div class="radio-primary">
<input type="radio id="selectId{{i}}" name="primaryRadio">
</td>
</tr>
</table>
<a (click)="clear()" [innerHTML]="clear"></a>
Following changes need to be done in .TS file:
clear(): void {
var ele = document.getElementsByName("primaryRadio");
for(var i=0;i<ele.length;i++) {
var element = ele[i] as HTMLInputElement;
element.checked = false;
}
}
Idea is, Radio buttons works with same NAME (HTML structure). Set the checked attribute of all radio elements with same name