Angular 2 : how to create radio buttons from enum and add two-way binding?

标签 angular radio-button two-way-binding

我正在尝试使用 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/

相关文章:

java - 如何根据选择的单选按钮打开特定 Activity ?

php - 如何使用 PHP 重复单选按钮

javascript - AngularJS 双向数据绑定(bind)被 setTimeout 取消

typescript - 在angular2中修改url时只改变dom的一部分

android - 选择其他单选按钮时,单选按钮组中的单选按钮不会取消选择

angular - ngIf 表达式检查后发生了变化

android - 使用 Android 架构组件将单向数据绑定(bind)转换为双向数据绑定(bind)

angular - 双向绑定(bind) - 嵌套对象 - Angular - 无法读取未定义的属性

javascript - 通过使用 es6 获取数组实例来滞后

Angular 4 - 如何正确拆除应用程序?