You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

50 lines
1.4 KiB

  1. import { Injectable } from '@angular/core';
  2. import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
  3. import { Contact, Name, Address } from '@nested-forms/contact';
  4. @Injectable({
  5. providedIn: 'root',
  6. })
  7. export class ContactFormService {
  8. constructor(private fb: FormBuilder) {}
  9. public createForm(model: Contact): FormGroup {
  10. return this.fb.group({
  11. name: this.createContactNameForm(model.name),
  12. addresses: this.createContactAddressListForm(model.addresses),
  13. });
  14. }
  15. public createContactNameForm(name: Name): FormGroup {
  16. return this.fb.group({
  17. firstName: [name ? name.firstName : ''],
  18. lastName: [name ? name.lastName : ''],
  19. middleName: [name ? name.middleName : ''],
  20. prefix: [name ? name.prefix : ''],
  21. suffix: [name ? name.suffix : ''],
  22. })
  23. }
  24. public createContactAddressListForm(addresses: Address[]): FormArray {
  25. const list: FormArray = this.fb.array([]);
  26. if (addresses) {
  27. addresses.forEach(addr => {
  28. list.push(this.createContactAddressForm(addr));
  29. });
  30. }
  31. return list;
  32. }
  33. public createContactAddressForm(addr: Address): FormGroup {
  34. return this.fb.group({
  35. line1: [addr ? addr.line1 : ''],
  36. line2: [addr ? addr.line2 : ''],
  37. city: [addr ? addr.city : ''],
  38. state: [addr ? addr.state : ''],
  39. postalCode: [addr ? addr.postalCode : ''],
  40. });
  41. }
  42. }