[英]Nested reactive forms in Angular
我正在尝试在我的 Angular 6 应用程序中动态创建一个嵌套的 FormArray。
我有一个报价单,其中包含报价项的集合
export class Quote {
quoteId: number;
quoteItems: QuoteItem[]
status: string;
}
export class QuoteItem {
quoteItemId: number;
description: string;
quoteItemDetails: QuoteItemDetail[]
}
export class QuoteItemDetail {
quoteItemDetailId: number;
rate: number;
quantity: number;
total: number;
}
我有一个包含 Quote 对象的表单,用户可以在其中单击一个按钮来添加和删除一个或多个 QuoteItem。
这是我初始化表单的代码:
ngOnInit() {
this.quoteForm = this.fb.group({
status: [''],
quoteItems: this.fb.array([])
});
this.addQuoteItem();
}
这就是我如何进行动态添加和删除工作:
get quoteItems() {
return this.quoteForm.get('quoteItems') as FormArray;
}
addQuoteItem() {
this.quoteItems.push(this.fb.group({
description: '',
quoteItemDetails: this.fb.array([])
}));
}
removeQuoteV2Item(index) {
this.quoteV2Items.removeAt(index);
}
还有我的 html:
<div formArrayName="quoteItems">
<div @items *ngFor="let item of quoteItems.controls; let contentIndex=index" [formGroupName]="contentIndex">
<input type="text" formControlName="description">
</div>
</div>
<p>
<a (click)="addQuoteItem()">Add Quote Item</a>
</p>
我想要做的是具有相同的功能,但对于我的 QuoteItemDetail 数组。 因此用户可以添加一个或多个quoteItems,并在其中添加一个或多个QuoteItemDetails。
我真的被困在第一点,我无法弄清楚如何获得表单数组评估器,这不能作为示例,因为我不确定如何传递索引:
get quoteItemDetails() {
return this.quoteItems.get('quoteItemDetails') as FormArray;
}
您将无法使用访问器来执行此操作。 访问器将为您提供对一个属性的引用。 但是正如您所说,在这种情况下,您需要一个索引来指定您需要的quoteItemDetails FormArray 引用(因为据我所知,您希望每个quoteItem 中有一个FormArray,因此每个quoteItem 可以有多个quoteItemDetails,对吗?)。
不过,我不认为这有什么问题。 不是像使用quoteItems那样使用访问器来执行它,而是必须使用一种方法来执行它,该方法采用您需要的一个参数,即索引。 像这样的东西:
quoteItemDetails(quoteItemIndex: number): FormArray {
return this.quoteItems.at(quoteItemIndex).get('quoteItemDetails') as FormArray;
}
然后你在模板上表示它:
<div formArrayName="quoteItems">
<div @items *ngFor="let item of quoteItems.controls; let contentIndex=index" [formGroupName]="contentIndex">
<input type="text" formControlName="description">
<div *ngFor="let quoteItemDetail of quoteItemDetails(contentIndex).controls; let detailIndex=index" [formArrayName]="detailIndex">
<input type="number" formControlName="description" />
</div>
</div>
</div>
我希望这可以帮助你。 我还没有测试代码,但解决方案应该是沿着这些路线的某个地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.