I have this form in parent component that process purchased items:
parent.component.ts:
this.rForm = fb.group({
'processedon' : [null, [Validators.required,dateIsBeforeOrOnToday2]],
'supplied_items_info':fb.group({
'item_manf':[null,[Validators.required]],
'item_brand':[null,[Validators.required]]
})
});
the supplied_items_info elements are also repeated in another form:
this.rForm2 = fb.group({
'supplied_items_info':fb.group({
'item_manf':[null,[Validators.required]],
'item_brand':[null,[Validators.required]]
})
});
I wanted to take the it out to a child component and define it there:
child.component.ts
import { Validators,FormControl,ControlContainer, FormGroupName,FormGroup } from '@angular/forms';
@Component({
selector: 'app-items-form',
viewProviders: [
{ provide: ControlContainer, useExisting: FormGroupName }
]
})
item_brand = new FormControl('',
[Validators.required]);
item_manf= new FormControl('',
[Validators.required]);
and insert them in the parent.component.html file:
<div formGroupName="supplied_item_info">
<app-item-form></app-item-form>
</div>
The issue is now I didn't really solve the problem as the parent.component.ts must still define the form fields. How can I define the item elements in a child component and inject them into a parent component so validation takes place in the child form but data is then submitted as part of the parent form?
First bind reusable formcontrols in a method and you can access that method in parent component using @ViewChild decorator.
Here's an example:
child.component.ts
child.component.html
and use Input decorator to send data from parent to child
parent.component.html:
parent.component.ts
Same way use in multiple forms wherever needed this reusable formControls.