In my Angular project, I am exploring the concept of nesting multiple reactive forms within different components.
For instance, I have a component called NameDescComponent
that includes a form with two inputs - one for name and one for description, along with a submit button.
The goal is to reuse this component across various pages and forms. Here's a snippet of the HTML code for the component:
<form [formGroup]="nameDescForm" (ngSubmit)="customEmit()">
<div fxLayout="row" fxLayoutGap="10px" fxFlex>
<mat-form-field>
<input matInput placeholder="Name" formControlName="name">
</mat-form-field>
<mat-form-field fxFlex>
<input matInput placeholder="Description" formControlName="description">
</mat-form-field>
</div>
<div fxLayout="column" fxLayoutGap="10px">
<button type="submit" mat-raised-button color="primary">
{{buttonText}}
</button>
<div>
</div>
</div>
</form>
And here's an excerpt from the corresponding TypeScript file:
public nameDescForm: FormGroup;
@Input() public buttonText: string;
@Output() public save: EventEmitter<any> = new EventEmitter<any>();
@Output() public nameDescFormEmit: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();
constructor(fb: FormBuilder) {
this.nameDescForm = fb.group({
'name': ['', Validators.required],
'description': ['']
});
}
public ngOnInit() {
console.log(this.nameDescForm);
this.nameDescFormEmit.emit(this.nameDescForm);
}
public customEmit() {
this.save.emit();
}
Furthermore, in a separate page where I include the NameDescComponent
, I embed it within another form like so:
<form [formGroup]="parentForm" (ngSubmit)="customEmit()">
<app-name-description (nameDescFormEmit)="getNameDescForm($event)" buttonText="Save" (save)="save()"></app-name-description>
<input type="test" formControlName="test">
</form>
Currently, I pass the nameDescFrom
data from its component to the ParentComponent
using Output and EventEmitter. Although this approach works, I find myself having to independently manage both forms' validity during submission.
I'm curious if there might be a more efficient way to handle this, perhaps accessing the nameDescFrom
directly within the parent form?
Thank you