I am fighting with Reactive Forms and nested FormArray. I am in the process of developing app to show clients with multiple addresses. FormArray supposed to hold multiple address and using *ngFor I would like to show them to the user.
Everything works, except I cannot add more them item to FormArray (Addresses) Even if I have specified 2 elements in the array I still get only one assigned.
What is wrong with my code?
address.component.ts
import { Component, OnInit } from '@angular/core';
import { ClientsService } from '../../../shared/clients.service';
import { FormArray } from '@angular/forms';
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css']
})
export class AddressComponent implements OnInit {
constructor(public clientService: ClientsService) { }
get Addresses(): FormArray{
return <FormArray>this.clientService.clientForm.get('Addresses');
}
ngOnInit(): void {}
}
clients.service.ts
import { Injectable } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Injectable({
providedIn: 'root'
})
export class ClientsService {
constructor(private fb: FormBuilder, private http: HttpClient) { }
clientForm = this.buildClientData();
initializeFormGroup() {
this.clientForm.patchValue({
Id: 0,
CompId: null,
NIP: null,
ClientRelation: '',
CompanyName: '',
BusinessType: '',
UsName: '',
Addresses: [{
Id: 0,
Type: 'Company',
Country: '',
Wojewodztwo: '',
Powiat: '',
Gmina: 'testo',
City: '',
StreetName: '',
StreetNo: '',
ApartmentNo: '',
PostalCode: '',
PostalCity: ''
},
{
Id: 1,
Type: 'Accomodation',
Country: '',
Wojewodztwo: '',
Powiat: '',
Gmina: 'testo',
City: '',
StreetName: '',
StreetNo: '',
ApartmentNo: '',
PostalCode: '',
PostalCity: ''
},
],
Phone: '',
Active: false,
Debtor: false,
Poa: '',
PoaPayment: ''
});
console.log(this.clientForm);
}
buildClientData(): FormGroup {
return this.fb.group ({
Id: 0,
CompId: null,
NIP: null,
ClientRelation: '',
CompanyName: '',
BusinessType: '',
UsName: '',
Addresses: this.fb.array([this.buildClientAddress()]),
Phone: '',
Active: false,
Debtor: false,
Poa: '',
PoaPayment: ''
});
}
buildClientAddress(): FormGroup {
return this.fb.group({
Id: null,
Type: '',
Country: '',
Wojewodztwo: '',
Powiat: '',
Gmina: '',
City: '',
StreetName: '',
StreetNo: '',
ApartmentNo: '',
PostalCode: '',
PostalCity: ''
});
}
}