Sign Up

Sign In

Forget Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask question.

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

  • 0

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?

Click to rate this post!
[Total: 0 Average: 0]
Share This Post
Share
  1. 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.

    • 0
Leave an answer

Leave an answer

Browse

close