我正在开发一个小型可重用组件,它可以设置单选按钮的样式并发出选定的值。
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);
}
}
该组件的实现方式如下:
<button-select #statusFilter
[choices]="['All', 'Active', 'Draft']"
[defaultChoice]="'All'"
[groupName]="'statusFilter'"
(valueChosen)="filterChosen('statusFilter', $event)"
</button-select>
Before adding [(ngModel)]="value" (ngModelChange)="choose($event)"
到按钮选择组件,[checked]="choice === defaultChoice"
指令正确设置checked
相关属性<input />
.
After添加[(ngModel)]
, only ng-reflect-checked="true"
被设置,这会阻止视觉样式显示默认值(因为我的 CSS 使用伪选择器)。
改变[(ngModel)]
for [ngModel]
没有效果。
为什么会发生这种情况以及如何解决它?