YulePale
YulePale

Reputation: 7686

How to uncheck a radio button on its second click Angular 2+

I am trying to implement Radio button uncheck on second click in Angular 2+ as done here in angularjs. I have an array of objects that get displayed using *ngFor, therefore I have multiple radio button groups in one form. I need an implementation that will onlt uncheck the said radio button/ All the implementations I have tried keep checking and unchecking multiple buttons while other implementations don't work at all.

This is my current code right now. How can I implement Radio button uncheck on second click using typescript?

Upvotes: 2

Views: 12934

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92367

If you don't want to use ngModel then you can use following approach

<div *ngFor="let item of items">
    <label>
        <input
            #radioInput
            type="radio"
            [value]="item.id"
            [checked]="item.checked"
            (input)="onChange(item, radioInput)"
        />
        <span>{{ item.label ? item.label : item.labelKey }}</span>
    </label>
</div>

and in .ts file


onChange(chosenItem: FieldRadioItem, inpCheckbox: HTMLInputElement) {

    inpCheckbox.checked = !inpCheckbox.checked;
    ...
}

Class FieldRadioItem contains only fields id, label and checked. Tested on Angular 11

Upvotes: 0

L. Kvri
L. Kvri

Reputation: 1713

Please try your code with more radio buttons. Is it works well, you able to try to un-select the selected radio button when you click it again? I means your stackblitz code: stackblitz.com/edit/angular-bootstrap4-jo5acq.

Upvotes: 0

Massimiliano Sartoretto
Massimiliano Sartoretto

Reputation: 1351

You need to bind the radio value to an ngModel and either listen to the ngModelChange or click event instead of change.

This answer might help you as well https://stackoverflow.com/a/42447116/4544288

Upvotes: 2

Related Questions