After adding [(ngModel)] to a radio button group, the default [checked] no longer works

msanford picture msanford · Feb 24, 2017 · Viewed 69.5k times · Source

I'm working on a small reusable Component which styles radio buttons and emits the selected values.

import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";

@Component({
    moduleId: module.id,
    selector: 'button-select',
    template: `<div class="toggle-group">
                    <div *ngFor="let choice of choices">
                        <input type="radio"
                               id="{{ groupName + choice }}"
                               name="{{groupName}}"
                               value="{{ choice }}"
                               [checked]="choice === defaultChoice"
                               [(ngModel)]="value"
                               (ngModelChange)="choose($event)" />
                        <label class="toggle-button"
                               for="{{ groupName + choice }}">{{ choice }}</label>
                    </div>
                </div>`,
    styleUrls: [
        'editableField.css',
        'buttonSelect.css'
    ]
})

export class ButtonSelectComponent implements OnInit {
    @Input() choices: string[];
    @Input() defaultChoice: string;
    @Input() groupName: string;
    @Input() value: string;

    @Output() valueChosen: EventEmitter<any> = new EventEmitter();

    ngOnInit() {
        this.choose(this.defaultChoice);
    }

    private choose(value: string) {
        this.valueChosen.emit(value);
    }
}

The component is implemented like so:

<button-select #statusFilter
               [choices]="['All', 'Active', 'Draft']"
               [defaultChoice]="'All'"
               [groupName]="'statusFilter'"
               (valueChosen)="filterChosen('statusFilter', $event)"
</button-select>

Before adding [(ngModel)]="value" (ngModelChange)="choose($event)" to the button-select Component, the [checked]="choice === defaultChoice" directive correctly set the checked attribute on the relevant <input />.

After adding the [(ngModel)], only ng-reflect-checked="true" gets set, which prevents the visual styling from showing the default value (since my CSS uses a pseudo-selector).

Changing [(ngModel)] for [ngModel] had no effect.

Why did this happen and how can I fix it?

Answer

mickdev picture mickdev · Feb 24, 2017

I think, you don't need this [checked]="choice === defaultChoice". Try this :

<input type="radio"
       id="{{ groupName + choice }}"
       name="{{groupName}}"
       [value]="choice"
       [(ngModel)]="defaultChoice"
       (ngModelChange)="choose($event)" />

When [value] = [(ngModel)] the radio is selected.