我创建这个网页,假设含有多种活性320交织(每个国家为例)。这些表格应创建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'.
用户,您使用的垫桌子?由数组进给垫桌子的工作,这是真的,该阵列可以FormControls数组,但它与表单控件数组辛勤工作。
垫表期待你一些像喂
[{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
})
}));