Refactor createForm() to provide composible factory methods

master
Kevin C. Coram 2019-12-31 13:49:46 -08:00
parent b8b2f8a3e7
commit cd7644a767
Signed by: kevin
GPG Key ID: 0342351B3D61AD35
1 changed files with 32 additions and 26 deletions

View File

@ -1,6 +1,6 @@
import { Injectable } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { Contact } from '@nested-forms/contact';
import { Contact, Name, Address } from '@nested-forms/contact';
@Injectable({
providedIn: 'root',
@ -9,35 +9,41 @@ export class ContactFormService {
constructor(private fb: FormBuilder) {}
public createForm(model: Contact): FormGroup {
const name = model.name;
const addresses: FormArray = this.fb.array([]);
const group = this.fb.group({
name: this.fb.group({
firstName: [name ? name.firstName : ''],
lastName: [name ? name.lastName : ''],
middleName: [name ? name.middleName : ''],
prefix: [name ? name.prefix : ''],
suffix: [name ? name.suffix : ''],
}),
addresses: addresses,
return this.fb.group({
name: this.createContactNameForm(model.name),
addresses: this.createContactAddressListForm(model.addresses),
});
}
if (model.addresses) {
model.addresses.forEach(addr => {
addresses.push(
this.fb.group({
line1: [addr ? addr.line1 : ''],
line2: [addr ? addr.line2 : ''],
city: [addr ? addr.city : ''],
state: [addr ? addr.state : ''],
postalCode: [addr ? addr.postalCode : ''],
}),
);
public createContactNameForm(name: Name): FormGroup {
return this.fb.group({
firstName: [name ? name.firstName : ''],
lastName: [name ? name.lastName : ''],
middleName: [name ? name.middleName : ''],
prefix: [name ? name.prefix : ''],
suffix: [name ? name.suffix : ''],
})
}
public createContactAddressListForm(addresses: Address[]): FormArray {
const list: FormArray = this.fb.array([]);
if (addresses) {
addresses.forEach(addr => {
list.push(this.createContactAddressForm(addr));
});
}
return group;
return list;
}
public createContactAddressForm(addr: Address): FormGroup {
return this.fb.group({
line1: [addr ? addr.line1 : ''],
line2: [addr ? addr.line2 : ''],
city: [addr ? addr.city : ''],
state: [addr ? addr.state : ''],
postalCode: [addr ? addr.postalCode : ''],
});
}
}