ControlValueAccessor with FormArray in Angular 2

I have a child component that deals with an array of input controls. I want to have formcontrol over a child component.

I am passing an array of json object, which would be the right way to bind the parent form to the child component of FormArray, which has 2 controls using the Validator needed for the first.

This is the initial code.

<h1>Child</h1> <div formArrayName="names"> <div *ngFor="let c of names.control"> <input formControlName="firstName"> <input formControlName="lastName"> </div> </div> 

The intention is to associate the parent form with the input control array in the child component. Also, the form will become invalid if one of the controls in the child component does not require a field.

http://plnkr.co/edit/HznCJfSEiSV28ERqNiWr?p=preview

+7
angular forms
source share
1 answer

You should use the formArrayName directive and *ngFor as follows:

 <form [formGroup]="form" (ngSubmit)="sayHello()"> <input formControlName="name"><br> <input formControlName="email"><br> <div formArrayName="username"> <div *ngFor="let user of username.controls; let i=index"> <my-child formControlName="i"></my-child> </div> </div> <button type="submit">Register</button> </form> 

And with FormBuilder you should also use FormArray .

 form = new FormGroup({ name: new FormControl('My Name'), username: new FormArray([ new FormControl("value"),// ControlValueAccesor is applied only to one control, not two. So you cannot use javascript object like you are using below this line. {firstName:"Anna", lastName:"Smith"}, {firstName:"Peter", lastName:"Jones"} ]) }); 

See this document for more information.

Case 2: FormGroup submission:

 form = new FormGroup({ name: new FormControl('My Name'), username: new FormArray([ new FormGroup({ firstName: new FormControl('Anna'), lastName: new FormControl('Smith') }), new FormGroup({ firstName: new FormControl('Peper'), lastName: new FormControl('Jones') }), ]) }) 

If you are trying to pass FormGroup as ngModel parameters, you cannot!

+1
source share

All Articles