问题
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