I've ran into a problem when trying to implement a nested angular FormGroup.
I'm using a specific scheme (interfaces between client and server) that describes the form inputs. I would like to create a FormGroup with certain validations, and find the easiest and efficient way for initializing the FormGroup with the scheme object.
The scheme object properties are object themselves, so foreach one of them I would like to create its own FormGroup. Also, the component that holds the main FormGroup contains child components which should be connected to the inner FromGroups (the keys of the scheme object).
For example:
MySchema: {
velocity:
{
speed: number,
direction: number
},
position:
{
x: number,
y: number
}
}
The main form should have 2 inner components - velocity component and position component.
Each child component should be connected to a child formGroup (velocity-component to the velocityGrouop and such..) and show the relevant validations.
The main form should be connected to the main FormGroup.
This is a small example, in our project the schema is much bigger and writing all the inner elements manually seems wrong.
I'm hoping you will be able to help me find a better way to do it.
Thanks.
Update
Maybe my question was not clear enough.. Is there a way to convert a big object to angular form groups / form control?
Each of my forms are containing objects that I received from the server and writing each element in fb manually seems wrong..
Thanks again and for everyone who already answered
Angular Reactive Form Supports Multiple Form Groups.
Component:
this.MySchemaFrom = this.fb.group({
velocity: this.fb.group({
speed: ['', Validators.required],
direction: ['', Validators.required]
}),
position: this.fb.group({
x: ['', Validators.required],
y: ['', Validators.required]
})
});
Template:
<form [formGroup]="MySchemaFrom">
<div formGroupName="velocity">
<legend> velocity </legend>
<div class="form-group">
<label for="name">Speed</label>
<input
type="text"
class="form-control"
id="name"
formControlName="speed">
</div>
<div class="form-group">
<label for="email">Direction</label>
<input
type="text"
class="form-control"
id="email"
formControlName="direction">
</div>
</div>
<div formGroupName="position">
<legend> position </legend>
<div class="form-group">
<label for="name">X</label>
<input
type="text"
class="form-control"
id="name"
formControlName="x">
</div>
<div class="form-group">
<label for="email">Y</label>
<input
type="text"
class="form-control"
id="email"
formControlName="y">
</div>
</div>
<button (click)="submit()">Submit</button>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With