我正在尝试使用 Angular2 语法从枚举定义创建单选按钮,并将该值绑定(bind)到具有该枚举类型的属性。
我的 html 包含:
<div class="from_elem">
<label>Motif</label><br>
<div *ngFor="let choice of motifChoices">
<input type="radio" name="motif" [(ngModel)]="choice.value"/>{{choice.motif}}<br>
</div>
</div>
在我的@Component 中,我声明了一组选择和值:
private motifChoices: any[] = [];
在我的@Component 的构造函数中,我按以下方式填写了选项:
constructor( private interService: InterventionService )
{
this.motifChoices =
Object.keys(MotifIntervention).filter( key => isNaN( Number( key )))
.map( key => { return { motif: key, value: false } });
}
单选按钮显示正确,现在我试图将所选值绑定(bind)到属性。但是,当我单击其中一个按钮时,值 choice.value 被设置为未定义。
最佳答案
好吧,我终于找到了解决方案。我目前正在使用 Angular 2 RC5。
我想绑定(bind)我的 radio 的枚举值是属性:
intervention.rapport.motifIntervention : MotifInterventions
在我的@Component 中,我声明了私有(private)成员以允许访问 html 模板中的枚举定义:
export class InterventionDetails
{
private MotifIntervention = MotifIntervention;
private MotifInterventionValues = Object.values(MotifIntervention).filter( e => typeof( e ) == "number" );
// model object:
private intervention: Intervention;
这是单选按钮的 HTML 代码:
<div *ngFor="let choice of MotifInterventionValues">
<input type="radio"
[(ngModel)]="intervention.rapport.motifIntervention"
[checked]="intervention.rapport.motifIntervention==choice"
[value]="choice" />
{{MotifIntervention[choice]}}<br>
</div>
[(ngModel)]="intervention.rapport.motifIntervention"
是双向的 绑定(bind),需要更新模型中的属性(在我的 案例intervention.rapport.motifIntervention
)[checked]="intervention.rapport.motifIntervention==choice"
是 如果值,则需要更新单选按钮组件 intervention.rapport.motifIntervention 被外部修改。[value]="choice"
是分配给我的属性的值 单选按钮被选中。{{MotifIntervention[choice]}}
为单选按钮的标签
关于 Angular 2 : how to create radio buttons from enum and add two-way binding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391910/