浏览代码

Refactor createForm() to provide composible factory methods

tags/part_1
Kevin C. Coram 1年前
父节点
当前提交
cd7644a767
签署人:: kevin GPG 密钥 ID: 0342351B3D61AD35
共有 1 个文件被更改,包括 31 次插入25 次删除
  1. +31
    -25
      libs/contact/src/lib/services/contact-form.service.ts

+ 31
- 25
libs/contact/src/lib/services/contact-form.service.ts 查看文件

@@ -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([]);
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 : ''],
})
}

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,
});
public createContactAddressListForm(addresses: Address[]): FormArray {
const list: FormArray = this.fb.array([]);

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 : ''],
}),
);
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 : ''],
});
}
}

正在加载...
取消
保存