Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material radio button change event Angular 4

I am trying to use the change output of an md-radio-buttons as follows:

<md-radio-group [(ngModel)]="selected">
    <md-radio-button *ngFor="let a of array" [value]="a"
                 (change)="radioChange()">
        {{a}}
    </md-radio-button>
</md-radio-group>

TS:

selected: string;
filter: any;

radioChange() {
    this.filter['property'] = selected;
    console.log(this.filter);
}

This always seems to be one step behind the radio buttons. i.e. when changing selection from radio A to radio B, it will console.log the value of radio A.

Any help would be much appreciated.

Cheers,

P

like image 536
Batters Avatar asked Sep 22 '17 10:09

Batters


2 Answers

This happens because the change event is fired before the model has been updated. So your selected property has the previous value. Change your code to following to get the event on (change):

<md-radio-group [(ngModel)]="selected">     <md-radio-button *ngFor="let a of array" [value]="a" (change)="radioChange($event)">         {{a}}     </md-radio-button> </md-radio-group> 

... and in your class, do the following:

import { MdRadioChange } from '@angular/material'; // ...  radioChange(event: MdRadioChange) {     this.filter['property'] = event.value;     console.log(this.filter); } 

Link to working demo.

like image 169
Faisal Avatar answered Sep 23 '22 04:09

Faisal


Set name property and change event to mat-radio-group in .html file:

<mat-radio-group 
    name="radioOpt1" 
    [(ngModel)]="selectedRadio"
    (change)="radioChange($event)">
    <mat-radio-button *ngFor="let opt of options" 
        [value]="opt">{{opt}}</mat-radio-button>
</mat-radio-group>

Then in component.ts file:

import { MatRadioChange } from '@angular/material';
...

radioChange($event: MatRadioChange) {
    console.log($event.source.name, $event.value);

    if ($event.source.name === 'radioOpt1') {
        // Do whatever you want here
    }
}
like image 35
Matheus Abreu Avatar answered Sep 23 '22 04:09

Matheus Abreu