67 lines
1.7 KiB
TypeScript
67 lines
1.7 KiB
TypeScript
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
|
|
import { Component, OnInit, OnDestroy } from '@angular/core';
|
|
import { Contact, ContactService } from '@nested-forms/contact';
|
|
import { Subscription } from 'rxjs';
|
|
|
|
@Component({
|
|
selector: 'nested-forms-root',
|
|
templateUrl: './app.component.html',
|
|
styleUrls: ['./app.component.css']
|
|
})
|
|
export class AppComponent implements OnInit, OnDestroy {
|
|
contact: Contact;
|
|
form: FormGroup;
|
|
|
|
private subscription: Subscription;
|
|
|
|
constructor(private fb: FormBuilder, private service: ContactService) {}
|
|
|
|
public ngOnInit() {
|
|
this.subscription = this.service
|
|
.loadContact()
|
|
.subscribe((data: Contact) => {
|
|
this.contact = data;
|
|
this.form = this.createForm();
|
|
});
|
|
}
|
|
|
|
public ngOnDestroy() {
|
|
if (this.subscription) {
|
|
this.subscription.unsubscribe();
|
|
}
|
|
}
|
|
|
|
private createForm(): FormGroup {
|
|
const name = this.contact.name;
|
|
|
|
const addresses: FormArray = this.fb.array([]);
|
|
|
|
const group = this.fb.group({
|
|
nameGroup: 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 (this.contact.addresses) {
|
|
this.contact.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;
|
|
}
|
|
}
|