I don't know how I could manage my form in my case. Imagine a form of 7 initial values :
- Name
- Company
- Address
- Product (repeatable)
- Serial Number (repeatable)
- Return Shipping Instructions
There is a button that creates a new instance of the Product and Serial Number input field component (in case there are more products). This would mean that I would need to create another component to make a nested form. The issue I am having is that I don't know how I could manage that.
I currently log my values like so :
console.log(this.parentForm.controls.name.value);
console.log(this.parentForm.controls.company.value);
console.log(this.parentForm.controls.email.value);
console.log(this.parentForm.controls.address.value);
console.log(this.parentForm.controls.returnInstructions.value);
But I am still trying to figure out how I could store my Product and SN values (as well as having a possibility to delete them). I was thinking about storing them in an array of objects that would be sent to the parent component (the one with the main form). The array would look like that : {Object1: product1, SN1, Object2: product2, SN2...} but event that, I don't know how to build it.
CodePudding user response:
This is the perfect use case for a form array. The validation below is just for example.
get products(): FormArray {
return this.fooForm.get('products') as FormArray;
}
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.fooForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3)]],
company: ['', [Validators.required, Validators.maxLength(50)]],
email: ['', [Validators.required, Validators.email]],
address: '',
products: this.fb.array([this.buildProduct()])
});
}
buildProduct(): FormGroup {
return this.fb.group({
name: ['', Validators.required],
serialNumber: ['', Validators.required],
});
}
And then remove like so:
removeProduct(index: number): void {
this.products.removeAt(index);
}
Add product like so:
addProduct(): void {
this.products.push(this.buildProduct());
}