Angular 2:如何从枚举创建单选按钮并添加双向绑定?

12

我正在尝试使用 Angular2 语法从一个枚举定义中创建单选按钮,并将值绑定到具有该枚举类型的属性。

我的 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 } });
}
单选按钮已正确显示,现在我想将所选值绑定到属性。但是当我单击其中一个按钮时,选择的值choice.value被设置为未定义。
2个回答

23

好的,最终我找到了解决方案。我目前正在使用Angular 2 RC5。

我想绑定我的单选按钮的枚举值是属性:

intervention.rapport.motifIntervention : MotifInterventions

在我的@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>
  • [(ngModel)]="intervention.rapport.motifIntervention" 是双向绑定,需要更新模型中的属性(在我的情况下是intervention.rapport.motifIntervention)。

  • [checked]="intervention.rapport.motifIntervention==choice" 在外部修改值 intervention.rapport.motifIntervention 后,需要更新单选按钮组件。

  • [value]="choice" 是当单选按钮被选中时分配给我的属性的值。

  • {{MotifIntervention[choice]}} 是单选按钮的标签。


2
这个救了我的命 [value]="choice" ... 非常奇怪,API文档甚至没有显示这个:https://angular.io/docs/ts/latest/api/forms/index/RadioControlValueAccessor-directive.html - Dan J
1
从Object.values中,我得到了“类型'ObjectConstructor'上不存在属性'values'。” - BBaysinger
我也遇到了“类型'ObjectConstructor'上不存在属性'values'”的问题。 - Waslap
自九月份以来,它可能已更改为[ngValue]。一旦在我的应用程序中验证,我将尽快更新我的帖子。 - Anthony Brenelière
1
“Property 'values' does not exist on type 'ObjectConstructor'.” 的问题可以通过使用 (<any>Object).values(MotifIntervention).filter(e => typeof(e) == 'number'); 来解决。 - Aster
我尝试了这段代码,只是将枚举更改为我的枚举。@AnthonyBrenelière,您对此angular6+代码有更新吗? - azulBonnet

1
有点晚了,但这对我有效:

  <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>

在哪里:

  • Items是选项的数组
  • ComponentID是组件的名称
  • GetOption是一个返回选项应该使用的标题的函数
  • GetValue是一个返回选项应该使用的值的函数
  • SelectionChanged用于更新模型

请注意,我不使用[(ngModel)]。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接