Angular 2:如何从枚举创建单选按钮并添加双向绑定? [英] Angular 2: how to create radio buttons from enum and add two-way binding?
问题描述
我正在尝试使用Angular2语法从枚举定义中创建单选按钮,并将该值绑定到具有该枚举类型的属性.
I'm trying to use Angular2 syntax to create radio buttons from an enum definition, and bind the value to a property that has the type of that enum.
我的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中,我声明了一组选择和值:
In my @Component, I declared the set of choices and values:
private motifChoices: any[] = [];
在我的@Component的构造函数中,我通过以下方式填充了选择:
And in the constructor of my @Component, I filled the choices the following way:
constructor( private interService: InterventionService )
{
this.motifChoices =
Object.keys(MotifIntervention).filter( key => isNaN( Number( key )))
.map( key => { return { motif: key, value: false } });
}
单选按钮正确显示,现在我试图将所选值绑定到属性.但是,当我单击按钮之一时,值choice.value设置为undefined.
The radio buttons are displayed correctly, now I seek to bind the value selected to a property. But when I click one of the buttons the value choice.value is set to undefined.
推荐答案
好吧,我终于找到了解决方案.我目前正在使用Angular 2 RC5.
Ok finally I found out the solution. I am currenly using Angular 2 RC5.
我想绑定我的收音机的枚举值是该属性:
The enum value I want to bind my radio is the property:
intervention.rapport.motifIntervention : MotifInterventions
在我的@Component中,我声明了私有成员以允许访问html模板中的枚举定义:
In my @Component I declared private members to give access to enum definition in the html template:
export class InterventionDetails
{
private MotifIntervention = MotifIntervention;
private MotifInterventionValues = Object.values(MotifIntervention).filter( e => typeof( e ) == "number" );
// model object:
private intervention: Intervention;
以下是单选按钮的HTML代码:
Here is HTML code for the radio buttons:
<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"
是双向的 绑定,则需要更新模型中的属性(在我的 情况intervention.rapport.motifIntervention
)[(ngModel)]="intervention.rapport.motifIntervention"
is two-way binding, it is required to update the property in the model (in my caseintervention.rapport.motifIntervention
)[checked]="intervention.rapport.motifIntervention==choice"
是 需要更新单选按钮组件的值 iation.rapport.motifIntervention在外部进行了修改.[checked]="intervention.rapport.motifIntervention==choice"
is required to update the radio buttons component if the value intervention.rapport.motifIntervention is modified externally.[value]="choice"
是在以下情况下分配给我的属性的值 单选按钮被选中.[value]="choice"
is the value that is assigned to my property when the radio button is selected.{{MotifIntervention[choice]}}
是单选按钮的标签这篇关于Angular 2:如何从枚举创建单选按钮并添加双向绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!