Jan Bürger
Jan Bürger

Reputation: 121

(change) when other radiobutton is checked

I have two radio buttons. I need to fire an event when button B is checked or unchecked. I can not bind any event to A.

<input type="radio" id="A" name="radiogrp" value="A">
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B" (change)="showOrHideElement()">
<label for="B">B</label>

It just works when the button B is checked, the event is not fired when I click on the other button. How can I listen to button changes of B without binding anything to A?

Upvotes: 2

Views: 72

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24404

you can use ngModelChange when you use ngModel everytime the value change the log() method will run.

<input type="radio" id="A" name="radiogrp" value="A" [(ngModel)]="radioValue" (ngModelChange)="log()">
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B"[(ngModel)]="radioValue" (ngModelChange)="log()" >
<label for="B">B</label>

demo 🔥🔥

in case you want to run the method if the B is selected you can just bind the event to the B element

<input type="radio" id="A" name="radiogrp" value="A" [(ngModel)]="radioValue" >
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B"[(ngModel)]="radioValue" (ngModelChange)="log()" >
<label for="B">B</label>

demo 🚀🚀

other option you can use reactive forms as a simple example using Form Control

<input type="radio" id="A" name="radiogrp" value="A" [formControl]="selection">
<label for="A">A</label>
<input type="radio" id="B" name="radiogrp" value="B" [formControl]="selection" >
<label for="B">B</label>

component

  selection= new FormControl('A')

  ngOnInit(){
      this.selection.valueChanges.subscribe(value =>{

        if (value == 'B') {
        console.log(`B is selected 👉 `,value)
        } else {

        console.log(`B is not selected 👉 `,value)
        }
      })
  }

demo 🌟🌟

Upvotes: 1

Related Questions