You can create the shifts form array on the parent i.e. Working day component and then pass the individual array controls as a FormGroup to the child shift component.
this.parentform = this.formBuilder.group({
name: new FormControl(),
shifts: new FormArray([]),
});
---- Template ----
<app-shift [form]="parentform.get('shifts').controls[index]"></app-shift>
By passing FormGroup to the child component, you can access its values/validators on the parent also.
Note: As you have mentioned, that shifts will be coming from API, you would need to iterate over the shifts array in response & create FormGroup with startDate/endDate properties.
Here is how it would work:
Shift component: Take FormGroup as an input.
@Input() form: FormGroup;
get shiftForm() {
return this.form as FormGroup;
}
In the parent component, create the form group & iterate over the shift FormArray.controls.
Parent HTML:
<div formArrayName="shifts">
<ng-container *ngFor="let shiftForm of shiftsArray.controls; let i = index">
<app-shift [form]="shiftForm"></app-shift>
</ng-container>
</div>
TS: On button click/ receiving API response, call addShift() method to add a new FormGroup in shifts control
addShift() {
const shiftForm = this.formBuilder.group({
startDate: new FormControl(''),
endDate: new FormControl(''),
});
this.shiftsArray.push(shiftForm);
}
Note: Recent versions of Angular are strict towards typecasting. Therefore you may need to typecast each shiftForm as FormGroup in the parent before passing to the child.
Here is a working stackblitz to demonstrate passing FormGroup from parent to child.
Shifts Componentthat creates inputs for start/end date? And you want to dynamically add this component inside theWorking Daytemplate withngForor something similar?