Reputation: 1596
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?
Upvotes: 3
Views: 11017
Reputation: 658067
update
Not applicable to the final Angular 2 release.
original
This might be what you're looking for:
@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]));
}
}
}
Upvotes: 4