Inline createForm method

The baseline application will be a better example of "everything in a single application" if it directly creates its form rather than using the library service.

This is definitely less DRY, but makes for a better example.
master
Kevin C. Coram 2019-09-07 21:55:50 -04:00
parent 3f5eb92ea7
commit 00577f888e
Signed by: kevin
GPG Key ID: 0342351B3D61AD35
1 changed files with 37 additions and 11 deletions

View File

@ -1,10 +1,6 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import {
Contact,
ContactService,
ContactFormService,
} from '@nested-forms/contact';
import { FormGroup, FormArray } from '@angular/forms';
import { Contact, ContactService } from '@nested-forms/contact';
import { FormGroup, FormArray, FormBuilder } from '@angular/forms';
import { Subscription } from 'rxjs';
@Component({
@ -18,17 +14,14 @@ export class AppComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(
private service: ContactService,
private formService: ContactFormService,
) {}
constructor(private service: ContactService, private fb: FormBuilder) {}
public ngOnInit() {
this.subscription = this.service
.loadContact()
.subscribe((data: Contact) => {
this.contact = data;
this.form = this.formService.createForm(data);
this.form = this.createForm(data);
});
}
@ -38,6 +31,39 @@ export class AppComponent implements OnInit, OnDestroy {
}
}
public createForm(model: Contact): FormGroup {
const name = model.name;
const addresses: FormArray = this.fb.array([]);
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) {
model.addresses.forEach(addr => {
addresses.push(
this.fb.group({
line1: [addr ? addr.line_1 : ''],
line2: [addr ? addr.line_2 : ''],
city: [addr ? addr.city : ''],
state: [addr ? addr.state : ''],
postalCode: [addr ? addr.postalCode : ''],
}),
);
});
}
return group;
}
get addresses(): FormArray {
return this.form.get('addresses') as FormArray;
}