DBK DBK - 1 year ago 61
TypeScript Question

When I console.log a user's radio button selection, what logs is always one behind

For some reason, when I console.log a user's radio button selection, what logs to the console is always one behind. Why would this be? I have a default radio button selection set to "all" for the initial state. When a user click's "Option A" what logs to the console is the "all" from the initial state. When I click again, this time on "Option B", what logs is "Option A" from the previous selection. Why is it one off? How can I resolve this?

public user: User;

public categories = [
{ value: 'T', display: 'All', count: 232 },
{ value: 'A', display: 'Choice A', count: 22 },
{ value: 'B', display: 'Choice B', count: 43 },
{ value: 'C', display: 'Choice C', count: 35 },
{ value: 'D', display: 'Choice D', count: 62 },

ngOnInit() {
this.user = {
category: this.categories[0].value

select(isValid: boolean, f: User) {
if (!isValid) return;

And the HTML:

<form #f="ngForm" novalidate>
<div class="form-group">
<div class="radio" *ngFor="let category of categories">
<input type="radio" name="category" [(ngModel)]="user.category" [value]="category.value" (click)="select(f.value, f.valid)">
<span class="num-results">{{category.count}}</span>

Answer Source

Use ngModelChange instead of click

(ngModelChange)="select(f.value, f.valid)"

The (click) event is processed before ngModel had the chance to update the form.

The order of bindings on an element doesn't define in what order events are processed.