I'm working with .Net Core 3.0 and Angular 8. I'm building a form using Angular's Reactive Forms and FormBuilder, with FormGroup and FormArray. Basically, I have two models which look like this in the .Net API:
public class Parent
{
[Required]
public string Name { get; set; }
[Required]
public List<Child> Children { get; set; }
}
public class Child
{
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
}
In Angular I'm using FormBuilder to build a form like this:
// In the component class
// this.fb is type FormBuilder
form = this.fb.group({
name: [''],
children: this.fb.array([])
});
// Later on, I build the form.children like this
for (var x = 0; x < 9; x++) {
this.form.get('children')
.push(this.fb.group({
name: [''],
description: ['']
});
}
Note the [Required]
attribute on the models in .Net. So if I submit my form without values for the required properties, .Net returns a response which looks like this:
"errors": {
"name": ["The Name field is required"],
"children[0].name": ["The Name field is required"],
"children[0].description": ["The Description field is required"],
// and so on
}
I can obviously tell my Angular form that the name
field has an error, because if I loop through the errors in that response I can say this.form.get('key')
where key
is each key in the errors
object. However, that does not seem to work for the children
FormArray.
So far the only way I've been able to get it to work is by manually parsing the error keys. That feels very wrong though, because I'm having to manually parse the index values from each of the children[index].fieldName
errors.
I'm aware of client side validation using built-in and customer validators in Angular. Those will also be in place, but I'd like to be able to utilize the API's 400 response in the event that something gets past the client validation.
Am I missing something? Is there a way to take the .Net HTTP 400 error response - specifically the errors
object - and add those errors to the correct FormGroup within the children
FormArray (e.g. children[0].name)? I suppose it's possible I'm using FormGroup and FormArray incorrectly due to lack of familiarity with Reactive Forms (this is my first time with them). But from the things I read, this felt correct to me.