Refactor createForm() to provide composible factory methods
parent
b8b2f8a3e7
commit
cd7644a767
|
@ -1,6 +1,6 @@
|
||||||
import { Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
|
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
|
||||||
import { Contact } from '@nested-forms/contact';
|
import { Contact, Name, Address } from '@nested-forms/contact';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
|
@ -9,35 +9,41 @@ export class ContactFormService {
|
||||||
constructor(private fb: FormBuilder) {}
|
constructor(private fb: FormBuilder) {}
|
||||||
|
|
||||||
public createForm(model: Contact): FormGroup {
|
public createForm(model: Contact): FormGroup {
|
||||||
const name = model.name;
|
return this.fb.group({
|
||||||
|
name: this.createContactNameForm(model.name),
|
||||||
const addresses: FormArray = this.fb.array([]);
|
addresses: this.createContactAddressListForm(model.addresses),
|
||||||
|
|
||||||
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,
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (model.addresses) {
|
public createContactNameForm(name: Name): FormGroup {
|
||||||
model.addresses.forEach(addr => {
|
return this.fb.group({
|
||||||
addresses.push(
|
firstName: [name ? name.firstName : ''],
|
||||||
this.fb.group({
|
lastName: [name ? name.lastName : ''],
|
||||||
line1: [addr ? addr.line1 : ''],
|
middleName: [name ? name.middleName : ''],
|
||||||
line2: [addr ? addr.line2 : ''],
|
prefix: [name ? name.prefix : ''],
|
||||||
city: [addr ? addr.city : ''],
|
suffix: [name ? name.suffix : ''],
|
||||||
state: [addr ? addr.state : ''],
|
})
|
||||||
postalCode: [addr ? addr.postalCode : ''],
|
}
|
||||||
}),
|
|
||||||
);
|
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 : ''],
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue