问题描述
我正在研究一个小的可重用组件,该组件可设置单选按钮的样式并发出选定的值.
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>
在添加[(ngModel)]="value" (ngModelChange)="choose($event)"
到按钮选择组件之前,[checked]="choice === defaultChoice"
指令在相关的<input />
上正确设置了checked
属性.
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 />
.
添加[(ngModel)]
后,仅设置 ng-reflect-checked="true"
,这将阻止视觉样式显示默认值(因为我的CSS使用了伪选择器).
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).
将[(ngModel)]
更改为[ngModel]
无效.
为什么会发生这种情况,我该如何解决?
推荐答案
我认为,您不需要此[checked]="choice === defaultChoice"
.试试这个:
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.
这篇关于将[(ngModel)]添加到单选按钮组后,默认的[已选中]不再起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!