Angular forms - access FormArray in child component template

后端 未结 1 2014
天涯浪人
天涯浪人 2021-01-24 09:42

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

相关标签:
1条回答
  • 2021-01-24 10:35

    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

    0 讨论(0)
提交回复
热议问题