我正在创建此页面,假定其中包含多个响应来源(例如,每个国家/地区)。这些表单应基于我从后端获取的json数组创建,以便用户可以看到当前设置是什么并单独更新。由于我不知道要获得多少这些数据集,因此我为我得到的每个数据集创建了一个主窗体和一个FormArray。但是,如果在表单验证程序将字段之一标记为无效时使用了FormArray,则整个表单都标记为无效(所有FormArray嵌套表格)。
我还尝试为可观察对象内部的每个数据集创建不同的形式,但这会给我以下错误
TS2339: Property 'countryForm' does not exist on type 'CountryComponent'.
这是我的TS
export class CountryComponentimplements OnInit {
// Form
countryForm: FormGroup;
ngOnInit() {
this.spinner.show();
this.GetCountryDef();
}
GetCountryDef() {
// tslint:disable-next-line:max-line-length
this.http.get(`https://api_call`).subscribe(
(data: any) => {
// Form
const CountryArray = new FormArray(data.map(item => new FormGroup({
country: new FormControl(item.country, Validators.required),
population: new FormControl(item.population, Validators.pattern(/\-?\d*\.?\d{1,5}/)),
GPD: new FormControl(item.GPD, Validators.pattern(/\-?\d*\.?\d{1,5}/))
.......
}),
));
this.countryForm= this.fb.group({
country: CountryArray ,
});
this.spinner.hide();
}
);
}
我的html
<td mat-cell *matCellDef="let country; let i = index">
<form style="width: inherit;" [formGroup]="countryForm">
<div formArrayName="country">
<div formGroupName={{i}}>
<label >populcation:</label>
<input matInput type="number" formControlName="population">
<label >GPD:</label>
<input matInput type="number" formControlName="GPD">
.......
</form>
</td>
所以我的问题是如何从可观察对象动态创建FromGroup或如何使验证器仅标记一个FormArray的错误?
================================================ ================================ @ AJT_82我已经尝试过了,但是即使加载后表单也没有显示。
所以我将其更改为
export class CountryComponentimplements OnInit {
// Form
//countryForm: FormGroup;
和
let countryForm: FormGroup; // Will change to to different form for each country after
countryForm= this.fb.group({
country: CountryArray ,
});
它给了我同样的错误
TS2339: Property 'countryForm' does not exist on type 'CountryComponent'.
答案 0 :(得分:0)
用户,您使用的是mat-table吗? Mat表格通过一个数组工作,确实该数组可以是FormControls的数组,但是使用Form Controls的数组很难。
垫子表希望您提供类似的东西
[{country:new FormControl(),population:new FormControl(),GDP:new FormControl()},
{country:new FormControl(),population:new FormControl(),GDP:new FormControl()},
{country:new FormControl(),population:new FormControl(),GDP:new FormControl()}
...]
相反,您可以使用数组创建普通表
<table >
<thead>
<tr >
<th >Country</th>
<th >Population</th>
<th >GDP</th>
</tr>
</thead>
<tbody *ngIf="formArray" [formGroup]="formArray">
<tr *ngFor="let item of formArray.controls;let i=index" [formGroupName]="i">
<td ><input formControlName="country"></td>
<td ><input formControlName="population"></td>
<td ><input formControlName="GDP"></td>
</tr>
</tbody>
</table>
我更喜欢引用数组本身。
如果我们在构造函数中注入FormBuilder
constructor(private fb:FormBuilder){}
我们的formArray可以像以前一样:
this.formArray=new FormArray(data.map(item=>{
return this.fb.group({
country:item.position,
population:item.name,
GDP:item.weight
})
}));