I have a parent component with a FormGroup. In my html code, I call several times a child component called my-text-input for the exemple. In this child component, I have one Input text with a specific attribut FormControlName. I want to add this control to my main form.
My main component with the formGroup :
<form class="form-horizontal" [formGroup]="mainForm" (ngSubmit)="save()"
novalidate>
<div class="devis-container">
...
<!-- first call of my child component -->
<my-input-text [parent]="mainForm" [model]="myObject.name" class="size-xl"
[required]="true"></my-input-text>
...
<!-- and in another part of the main form, another declaration -->
<my-input-text [parent]="mainForm" [model]="myObject.surname" class="size-
xl" [required]="true"></my-input-text>
...
</div>
</form>
The HTML of my child component :
<form [formGroup]="parent" name="inputTextForm">
<input type="text" formControlName="textField" placeholder="{{placeholder}}" class="domia-input"/>
...
</form>
So my issue is that I don't know how to add my control 'textField' to my main form. I tried this :
export class MyInputTextComponent extends InputBaseComponent implements OnInit {
...
@Input()
parent: FormGroup;
...
ngOnInit() {
this.parent.addControl('textField',
new FormControl('',
Validators.compose([conditionalRequired(this.required),
Validators.pattern(this.regex),
Validators.minLength(this.minlength),
Validators.maxLength(this.maxlength)]))
);
this.parent.controls.textField.setValue(this.model);
}
...
But the values of two "my input text" are the same. I found it is logical because it is the same form control I think. So, I tried another solution in the OnInit method of my child component :
this.parent = this.formBuilder.group({
textField: [this.model, conditionalRequired(this.required)]
});
In this case, the values are ok but I don't see this control in my mainForm. I think it is logical because I don't add my control to my parent/main form.
I tried to find some example on the official documentation page but I didn't find this specific case. Another solution should be to declare the control textField in the method BuildForm of my main component but I would like to find another solution and declare the control in the child component.
Thank you for your help.
FormArray, and for each of thoseFormControls, you would create this form control. - Giora Guttsait