71 lines
1.8 KiB
TypeScript
71 lines
1.8 KiB
TypeScript
import { Component, OnInit, OnDestroy } from '@angular/core';
|
|
import { Contact, ContactService } from '@nested-forms/contact';
|
|
import { FormGroup, FormArray, FormBuilder } from '@angular/forms';
|
|
import { Subscription } from 'rxjs';
|
|
|
|
@Component({
|
|
selector: 'base-root',
|
|
templateUrl: './app.component.html',
|
|
styleUrls: ['./app.component.css'],
|
|
})
|
|
export class AppComponent implements OnInit, OnDestroy {
|
|
contact: Contact;
|
|
form: FormGroup;
|
|
|
|
private subscription: Subscription;
|
|
|
|
constructor(private service: ContactService, private fb: FormBuilder) {}
|
|
|
|
public ngOnInit() {
|
|
this.subscription = this.service
|
|
.loadContact()
|
|
.subscribe((data: Contact) => {
|
|
this.contact = data;
|
|
this.form = this.createForm(data);
|
|
});
|
|
}
|
|
|
|
public ngOnDestroy() {
|
|
if (this.subscription) {
|
|
this.subscription.unsubscribe();
|
|
}
|
|
}
|
|
|
|
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.line1 : ''],
|
|
line2: [addr ? addr.line2 : ''],
|
|
city: [addr ? addr.city : ''],
|
|
state: [addr ? addr.state : ''],
|
|
postalCode: [addr ? addr.postalCode : ''],
|
|
}),
|
|
);
|
|
});
|
|
}
|
|
|
|
return group;
|
|
}
|
|
|
|
get addresses(): FormArray {
|
|
return this.form.get('addresses') as FormArray;
|
|
}
|
|
}
|