【问题标题】:How to implement radio buttons with ngControl (AngularJS2)?如何使用 ngControl (AngularJS2) 实现单选按钮?
【发布时间】:2016-07-30 20:05:25
【问题描述】:

我有一个关于如何使用 ngControl 在我的表单中实现单选按钮的问题

这是模板的代码:

<div class="form-group">
    <label class="radio-inline" *ngFor="#size of formModel.sizes">
        <input type="radio" ngControl="ourSize" #ourSize="ngForm" value="{{ size }}" >
        {{ size }}
    </label>
</div>

这是模型的代码:

this.formModel = {
        sizes: ['asd1', 'asd2', 'asd3']
}

我有这样一个错误:

附:我已经检查了另一个答案Angular2 - Radio Button Binding 但这对我没有帮助(

【问题讨论】:

  • 请创建一个允许重现问题的 Plunker。链接问题的答案包含一个可用作模板的示例。
  • 为什么需要 20 多个文件来证明 &lt;input type="radio" 的问题?
  • @GünterZöchbauer,对不起,必需品在 04 个文件夹中

标签: radio-button angular angular2-template


【解决方案1】:

您需要以这种方式使用无线电输入:

@Component({
  selector: 'my-app', 
  template: `
    <form>
      <div class="form-group">
        <label class="radio-inline" *ngFor="#size of formModel.sizes; #i=index">
        <input type="radio" [(ngModel)]="formModel.sizes[i]" #ctrl="ngForm" ngControl="sizeCtrl" name="size"/>
        {{ size.value }}
      </label>
    </div>
    Test: {{ctrl?.value}}
    Values: {{formModel | json}}
  </form>
`
})
export class AppComponent {
  constructor() {
    this.formModel = {
      sizes: [
        new RadioButtonState(true, 'asd1'),
        new RadioButtonState(false, 'asd2'),
        new RadioButtonState(false, 'asd3')
      ]
    };
  }
}

单选按钮状态会根据所选内容进行更新。这个级别好像不能用控件了……

请看这个plunkr:https://plnkr.co/edit/kHJyq3N5ZtoNyAPz6Kbc?p=preview

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 2020-11-19
    • 2013-05-29
    • 2020-12-04
    • 1970-01-01
    • 2010-11-28
    • 2015-10-31
    • 1970-01-01
    相关资源
    最近更新 更多