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),
|
||||||
|
addresses: this.createContactAddressListForm(model.addresses),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const addresses: FormArray = this.fb.array([]);
|
public createContactNameForm(name: Name): FormGroup {
|
||||||
|
return this.fb.group({
|
||||||
const group = this.fb.group({
|
|
||||||
name: this.fb.group({
|
|
||||||
firstName: [name ? name.firstName : ''],
|
firstName: [name ? name.firstName : ''],
|
||||||
lastName: [name ? name.lastName : ''],
|
lastName: [name ? name.lastName : ''],
|
||||||
middleName: [name ? name.middleName : ''],
|
middleName: [name ? name.middleName : ''],
|
||||||
prefix: [name ? name.prefix : ''],
|
prefix: [name ? name.prefix : ''],
|
||||||
suffix: [name ? name.suffix : ''],
|
suffix: [name ? name.suffix : ''],
|
||||||
}),
|
})
|
||||||
addresses: addresses,
|
}
|
||||||
});
|
|
||||||
|
|
||||||
if (model.addresses) {
|
public createContactAddressListForm(addresses: Address[]): FormArray {
|
||||||
model.addresses.forEach(addr => {
|
const list: FormArray = this.fb.array([]);
|
||||||
addresses.push(
|
|
||||||
this.fb.group({
|
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 : ''],
|
line1: [addr ? addr.line1 : ''],
|
||||||
line2: [addr ? addr.line2 : ''],
|
line2: [addr ? addr.line2 : ''],
|
||||||
city: [addr ? addr.city : ''],
|
city: [addr ? addr.city : ''],
|
||||||
state: [addr ? addr.state : ''],
|
state: [addr ? addr.state : ''],
|
||||||
postalCode: [addr ? addr.postalCode : ''],
|
postalCode: [addr ? addr.postalCode : ''],
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return group;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue