Refactor createForm() to provide composible factory methods
parent
b8b2f8a3e7
commit
cd7644a767
|
@ -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;
|
||||
return this.fb.group({
|
||||
name: this.createContactNameForm(model.name),
|
||||
addresses: this.createContactAddressListForm(model.addresses),
|
||||
});
|
||||
}
|
||||
|
||||
const addresses: FormArray = this.fb.array([]);
|
||||
|
||||
const group = this.fb.group({
|
||||
name: this.fb.group({
|
||||
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 : ''],
|
||||
}),
|
||||
addresses: addresses,
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
if (model.addresses) {
|
||||
model.addresses.forEach(addr => {
|
||||
addresses.push(
|
||||
this.fb.group({
|
||||
public createContactAddressListForm(addresses: Address[]): FormArray {
|
||||
const list: FormArray = this.fb.array([]);
|
||||
|
||||
if (addresses) {
|
||||
addresses.forEach(addr => {
|
||||
list.push(this.createContactAddressForm(addr));
|
||||
});
|
||||
}
|
||||
|
||||
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 : ''],
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue