Button Angular 2:如何从enum创建单选按钮并添加双向绑定?
我尝试使用Angular2语法从枚举定义创建单选按钮,并将值绑定到具有该枚举类型的属性 我的html包含:Button Angular 2:如何从enum创建单选按钮并添加双向绑定?,button,angular,binding,radio,two-way,Button,Angular,Binding,Radio,Two Way,我尝试使用Angular2语法从枚举定义创建单选按钮,并将值绑定到具有该枚举类型的属性 我的html包含: <div class="from_elem"> <label>Motif</label><br> <div *ngFor="let choice of motifChoices"> <input type="radio" name="motif" [(ngModel)]="choice.va
<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的构造函数中,我用以下方式填写了选项:
constructor( private interService: InterventionService )
{
this.motifChoices =
Object.keys(MotifIntervention).filter( key => isNaN( Number( key )))
.map( key => { return { motif: key, value: false } });
}
单选按钮显示正确,现在我寻求将所选值绑定到属性。但是当我单击其中一个按钮时,value choice.value被设置为undefined。确定最后我找到了解决方案。我现在使用的是角2 RC5 要绑定我的收音机的枚举值是属性:
intervention.rapport.motif干预:motif干预
在my@Component中,我声明了私有成员以允许访问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>
{{motif[choice]}}
是双向的 绑定时,需要更新模型中的属性(在我的 案例[(ngModel)]=“干预。融洽。干预”
)干预。融洽关系。干预
是 需要更新单选按钮组件,如果值 干预。融洽。干预是外部修改的[选中]=“干预.融洽关系.干预==选择”
是在 单选按钮被选中[value]=“choice”
是单选按钮的标签{{[choice]}
<tr *ngFor="let Item of Items; let idx = index" style="line-height: 10px;">
<td style="font-size:11px;padding-right: 10px;">{{ GetOption(Item) }}</td>
<td><input type="radio" [attr.name]="ComponentID" [id]="ComponentID"
[value]="GetValue(Item)" [checked]="value == GetValue(Item)" (change)="SelectionChange(GetValue(Item))"></td>
</tr>
{{GetOption(项目)}
其中:
- Items是一个选项数组
- ComponentID是组件的名称
- GetOption是一个函数,它返回选项所包含的标题 应该使用
- GetValue是一个函数,它返回 选项应使用
- SelectionChanged用于更新模型
请注意,我没有使用[(ngModel)]这救了我的命[value]=“choice”。。。非常奇怪,api文档甚至没有显示这一点:从Object.values中,我得到“属性'values'在类型'ObjectConstructor'上不存在”。“我还得到了“属性'values'在类型'ObjectConstructor'上不存在”它可能自9月份以来已更改为[ngValue]。在我的应用程序中验证后,我将立即更新我的poste。类型“ObjectConstructor”上不存在“属性“values”的问题。可以通过使用(Object).values(Motif.filter)(e=>typeof(e)='number')解决;
<tr *ngFor="let Item of Items; let idx = index" style="line-height: 10px;">
<td style="font-size:11px;padding-right: 10px;">{{ GetOption(Item) }}</td>
<td><input type="radio" [attr.name]="ComponentID" [id]="ComponentID"
[value]="GetValue(Item)" [checked]="value == GetValue(Item)" (change)="SelectionChange(GetValue(Item))"></td>
</tr>