thesystem
thesystem

Reputation: 604

Change boolean on (change) event

I am trying to use a boolean to detect whether a radio button in a form has been checked or not.

(I left out unneccessary code for both HTML and TS files)

HTML:

<mat-radio-button (change)="toggleEditable($event)" value="overdraft">Overdraft</mat-radio-button>

TypeScript:

overdraft = false;

toggleEditable(event) {
  if ( event.target.checked ) {
    this.overdraft = true;
  }
}

The event is not fired, because when I try to click the radio button and submit the form, overdraft is not set to true. HOWEVER, if I use a (click) event instead of (change), it works fine, BUT (click) events come with the disadvantage that you have to double-click the radio-buttons for the visual selection to appear, and thus I feel it a neccessity to use (change) (see more here: mat-checkbox does not check if condition is false (only on double click)).

How do I solve this issue, so that when I click the radio-button, my (change) event is fired and overdraft is set to true without using the (click)-events that come with UI-issues?

SOLUTION:

If you want to fetch the actual value of the mat-radio-button, you will need to make the following changes:

1) Instead of using [value]="overdraft" in HTML, use value without square brackets, such as this: <mat-radio-button value="overdraft">Overdraft</mat-radio-button>

2) In your TypeScript code, you can now access the value property from HTML:

valueChanged(event: MatRadioChange) {
  console.log(event.value); //will log the value for the button you clicked
}

Upvotes: 1

Views: 5940

Answers (3)

The Fabio
The Fabio

Reputation: 6240

Have you tried using ngModel?

it might be as simple as:

<mat-radio-group  [(ngModel)]="selectedValue" (change)="valueChanged($event)">
  <mat-radio-button value="overdraft">Overdraft</mat-radio-button>
  <mat-radio-button value="otherValue">Other</mat-radio-button>
</mat-radio-group>

And in your controller your could have:

valueChanged(event) {
    this.overdraft = (event.value ==='overdraft');
}

Upvotes: 2

connectedMind
connectedMind

Reputation: 439

  1. Have you looked at what console.log(event.target.checked) gives you back?
  2. Angular 2 radio button events try <input type="radio" "toggleEditable($event)" value="overdraft">Overdraft</input> If it works than, maybe it is a problem with mat-radio-button
  3. Material radio button change event Angular 4 suggests that you need a different type of event:

    import { MdRadioChange } from '@angular/material'; ... toggleEditable(event: MdRadioChange) {...}

Upvotes: 1

Homer
Homer

Reputation: 37

You can also modify the value directly in the HTML when change event is triggered:

<mat-radio-button (change)="overdraft = !overdraft; display()" [value]="overdraft">Overdraft</mat-radio-button>
  overdraft = false;
  display() {
    console.log(this.overdraft);
  }

The display function is only here for demonstration purpose ;)

Upvotes: 0

Related Questions