【发布时间】:2020-08-18 03:39:16
【问题描述】:
我正在与 Reactive Forms 和嵌套 FormArray 作斗争。 我正在开发应用程序以向具有多个地址的客户显示。 FormArray 应该保存多个地址并使用 *ngFor 我想向用户展示它们。
一切正常,除了我无法将更多项目添加到 FormArray(地址) 即使我在数组中指定了 2 个元素,我仍然只分配了一个。
我的代码有什么问题?
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: ''
});
}
}
【问题讨论】:
-
您被添加了一个对象到 buildClientAddress 的表单组中。如果你添加两组对象,你会得到另一组。
-
@Muthupriya,哇,你是对的。这是一项检查它是否有效的测试。如果我有动态更改地址数量怎么办?
-
@Muthupriya,你应该把它作为 anwser 发布,这样我才能接受它。
标签: angular angular-reactive-forms formarray