I'm new to Reactive Forms, I use to work with template driven forms.
I'm following the tutorial here: https://angular-templates.io/tutorials/about/angular-forms-and-validations
I have a User Class:
export class User {
public pseudo: string;
public email: string;
public password: string;
public constructor(init?: User) {
Object.assign(this, init);
}
}
And I got my FormGroups in a component:
this.matching_passwords_group = new FormGroup(
{
password: new FormControl(
'',
Validators.compose([
Validators.minLength(5),
Validators.required,
Validators.pattern(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$'
)
])
),
confirm_password: new FormControl('')
},
(formGroup: FormGroup) => {
return PasswordValidator.areEqual(formGroup);
}
);
// user details form validations
this.userDetailsForm = this.fb.group({
pseudo: new FormControl('', Validators.required),
email: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])
),
matching_passwords: this.matching_passwords_group,
terms: new FormControl(false, Validators.pattern('true'))
});
}
As you can see there's a nested formGroup for password confirmation (to check that both password are equals).
Then when user clicks on submit I want to transform my formGroup values into my User object.
I followed what's recommended here: Reactive Forms correctly convert Form Value to Model Object
Here my submit method:
onSubmitUserDetails(value) {
this.newUser = new User(this.userDetailsForm.value);
}
But obviously, with the nested password formGroup I don't have what I need in this.newUser:
{email: "test@test" matching_passwords: {password: "Test1", confirm_password: "Test1"} pseudo: "test" terms: true}
I could set values one by one but could be very long for bigger forms. Is there any handy way to set formGroup values into a class and solve problem with the nested password formGroup? How are we supposed to achieve that?
Is the best solution to have my User object reflecting exactly the formGroups structure, and then exclude useless fields (like password confirmation) when I send my object to the API?
Also what if I had a nested object in my User class, let say a collection of Books for instance, how am I supposed to transform nested FormGroups to match with the classes structure?