【发布时间】:2017-08-13 14:49:49
【问题描述】:
我有一个要求,我想实现逻辑以动态地将对象数组数据分配给输入控件,并且基于更新我想更新我的数组以及我想触发验证以检查控件中输入的名称/数据是否有重复条目。 为了验证,我使用了 ReactiveForm 模块。但我面临以下 2 个问题 –
- 我如何创建相同的数组结构以便成功 验证我可以直接将更新后的结构传递给api吗?
- 我如何将数组对象中的 id 分配给 formControlName,目前我用循环索引分配它。
plunkar 参考这里 - https://plnkr.co/edit/RSBpT0sFSI1GDCp6K7VR?p=preview
组件:
@Component({
selector: 'my-app',
template: `
<div>
<h3> Custom Group Validation</h3>
<form [formGroup]="myForm">
<div class="left">
names: <br>
<div formArrayName="names">
<div *ngFor="let item of namesArray.controls; let i = index">
<input type="text" [formControlName]="i">
<button (click)="removeAt(i)">X</button><br>
</div>
</div>
<div *ngIf="namesArray.hasError('duplicate')">
duplicate entries
</div>
<pre>Array value: <br>{{namesArray.value | json}}</pre>
</div>
</form>
</div>
`
})
类(摘要):
namesArray:FormArray = new FormArray([], this.customGroupValidation );
dataArray: { custId: number, customerName: string }[] = [
{ custId: 101, customerName: 'John' },
{ custId: 102, customerName: 'Mike' },
{ custId: 103, customerName: 'Julia' }];
ngOnInit():void{
for(let ele of this.dataArray){
this.namesArray.push(
new FormControl(ele.customerName)
);
}
}
感谢任何帮助!
【问题讨论】:
标签: angular angular2-forms reactive-forms