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
parent
3f5eb92ea7
commit
00577f888e
|
@ -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;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue