1

I have a component that takes several FormControls and FormArrays as inputs. I'm accessing the FormControls from the child component like this:

[formControl]="control"

This works fine, but I can't find a way to do the same with a FormArray. There doesn't appear to be a directive for it. I would like to avoid passing in a bunch of strings and accessing via formControlName and formArrayName if possible. Is there a way to do this?

1 Answer 1

3

Update there was a type error, jsut corrected

You can use a FormArray like a FormGroup, but be carefully with the "notation", if normally we use [formGroup]="i", now we use [formGroup]="group".

It's only think about what is myFormArray.controls

<form [formGroup]="myFormArray">
  <div *ngFor="let group of myFormArray.controls;let i=index" [formGroup]="group">
    <input formControlName="prop1">
    <div *ngIf="group.get('prop1').invalid">Prop1 Required</div>
    <input formControlName="prop2"/>
    <div *ngIf="group.get('prop2').invalid">Prop2 Required</div>
  </div>
</form>

myFormArray=new FormArray([
    new FormGroup({
      prop1:new FormControl('',Validators.required),
      prop2:new FormControl('',Validators.required)
    })
  ])

If your formArray is a FormArray of controls use directly formControl

<form [formGroup]="myFormArray2">
  <div *ngFor="let group of myFormArray2.controls">
    <input [formControl]="group">
    <div *ngIf="group.invalid">Required</div>
  </div>
</form>

myFormArray2=new FormArray([
    new FormControl('',Validators.required),
    new FormControl('',Validators.required)
  ])

See in stackblitz

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.