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

I am working on a small reusable component that creates switches and emits 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 as follows:

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

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

After adding, it is [(ngModel)]set only ng-reflect-checked="true", which does not allow the visual style to show the default value (since my CSS uses a pseudo selector).

The change [(ngModel)]for [ngModel]had no effect.

Why did this happen and how can I fix it?

+4
2

, [checked]="choice === defaultChoice". :

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

[value] = [(ngModel)] .

+10

, :

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

... . , / , .

+1

Source: https://habr.com/ru/post/1670769/


All Articles