在angular2控制阵列中使用单选按钮 [英] Using Radio buttons in angular2 Control Array

查看:61
本文介绍了在angular2控制阵列中使用单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有一个由控件组组成的控件数组,并在模板中循环控件数组以创建单选按钮.我可以选择所有单选按钮,即使它们属于不同的控制组并具有不同的名称...我在这里做了一个插件演示

Hello I have a control array which consists of control group, and the looping the control array in the template to create radio buttons. I am able to select all the radio buttons eventhough they belong to the different control group and has different name for them...I have made a plunker demo here http://plnkr.co/edit/jTMZUCj5JVFazlZo7e4W?p=preview (the plunker demo is in beta 9) ... When i remove the [ngFormControl] it works perfectly... can somebody please tell me the correct way to implement that?

  ArrayData=['abhi','rahul'];

ArrayControl=new ControlArray([]);

constructor(fb: FormBuilder) {  

this.ArrayControl=new ControlArray([]);

for(var i=0;i<this.ArrayData.length;i++){
  let myForm = fb.group({
  'Male':  ['', Validators.required]  ,
  'Female':  ['', Validators.required]
}); 

  this.ArrayControl.push(myForm);
}

}

这就是我创建控件数组的方式...

This is how i am creating the control array...

        <div *ngFor="#control of ArrayControl.controls;#i=index">
      <input type="radio" name="{{i}}" value="male" [ngFormControl]="control.controls['Male']"> Male<br>
      <input type="radio" name="{{i}}" value="female" [ngFormControl]="control.controls['Female']"> Female<br>
      <hr>
    </div>

通过这种方式,我正在循环模板...有人可以告诉我我在哪里做错了吗?

In this way i am looping the template... Can somebody please tell me where i am doing wrong?

推荐答案

更新

不适用于最终的Angular 2版本.

Not applicable to the final Angular 2 release.

原始

这可能是您要寻找的:

@Component({
  selector: 'my-app',
  directives: [REACTIVE_FORM_DIRECTIVES],    
  template: `
<div class="ui raised segment"> 
  <h3>Select Gender</h3>
  <form [formGroup]="form">
    <div formArrayName="arr">
      <div *ngFor="let item of arrayData; let i=index">
        <div>{{item}}</div>
        <input type="radio" [formControlName]="i" value="male"> Male<br>
        <input type="radio" [formControlName]="i" value="female"> Female<br>
        <hr>
      </div>
    </div>
  </form>
  <div>data: {{form.value | json}}</div>
</div>  

  `
})
export class AppComponent { 
  arrayData=['abhi','rahul'];

  //gender = new FormControl('', [Validators.required]);
  arr = new FormArray([]);

  constructor() {  
    this.form=new FormGroup({ 'arr': this.arr });
    console.log(this.form);
    for(var i=0; i < this.arrayData.length; i++){
      this.arr.push(new FormControl('', [Validators.required]));
    } 
  }
}

> 插播示例

这篇关于在angular2控制阵列中使用单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆