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

Ant*_*ère 11 binding button radio two-way angular

我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)

在我的@Component中,我声明了一组选择和值:

private motifChoices: any[] = [];
Run Code Online (Sandbox Code Playgroud)

在@Component的构造函数中,我按以下方式填充选项:

constructor( private interService: InterventionService )
{
    this.motifChoices =
        Object.keys(MotifIntervention).filter( key => isNaN( Number( key )))
            .map( key => { return { motif: key, value: false } });
}
Run Code Online (Sandbox Code Playgroud)

单选按钮显示正确,现在我试图将选定的值绑定到属性.但是,当我单击其中一个按钮时,值choice.value将设置为undefined.

Ant*_*ère 20

好吧我终于找到了解决方案.我目前正在使用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;
Run Code Online (Sandbox Code Playgroud)

这是单选按钮的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>
Run Code Online (Sandbox Code Playgroud)
  • [(ngModel)]="intervention.rapport.motifIntervention"是双向绑定,需要更新模型中的属性(在我的情况下intervention.rapport.motifIntervention)

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

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

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

  • 这节省了我的生命[value] ="选择"...非常奇怪,api doc甚至没有显示这个:https://angular.io/docs/ts/latest/api/forms/index/RadioControlValueAccessor-directive. HTML (2认同)