The easiest way to create a simple Reactive Form is to use a single Angular component to build and display the form. In this example application, an asynchronous call to an API is simulated. The `Contact` object thus obtained is used to create and initialize a `FormGroup` using the Angular `FormBuilder`.
```typescript
public ngOnInit() {
this.subscription = this.service
.loadContact()
.subscribe((data: Contact) => {
this.form = this.createForm(data);
});
}
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;
}
```
The component's template remders input controls for the Contact's name, and iterates over the array of addresses to render controls to edit each one.