Angular forms - access FormArray in child component template

若如初见. 提交于 2019-12-02 10:41:47

问题


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:


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



来源:https://stackoverflow.com/questions/55641362/angular-forms-access-formarray-in-child-component-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!