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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…