Angular 迭代角反应形式
我有一个动态创建的角度反应形式 我有一个函数,当“rate”或“quantity”字段更改时调用该函数。我想迭代这个表单,将每个项目的速率和数量相乘,然后将它们加在一起,得到一个总数 我该怎么做?我试过使用.forEach,但在Formarray上似乎不起作用 这是我表单的json结构:Angular 迭代角反应形式,angular,Angular,我有一个动态创建的角度反应形式 我有一个函数,当“rate”或“quantity”字段更改时调用该函数。我想迭代这个表单,将每个项目的速率和数量相乘,然后将它们加在一起,得到一个总数 我该怎么做?我试过使用.forEach,但在Formarray上似乎不起作用 这是我表单的json结构: { "quoteDate": "2019-01-11T11:00:00", "quoteItems": [ { "description": "", "quoteLine
{
"quoteDate": "2019-01-11T11:00:00",
"quoteItems": [
{
"description": "",
"quoteLineItems": [
{
"rate": 8,
"quantity": 78,
},
{
"rate": 2,
"quantity": 32,
}
]
},
{
"description": "",
"quoteLineItems": [
{
"rate": 24,
"quantity": 5,
}
]
},
{
"description": "",
"quoteLineItems": [
{
"rate": 1,
"quantity": 2145,
}
]
}
]
}
这就是我创建表单的方式:
createForm() {
this.quoteForm = this.fb.group({
quoteDate: [this.quote.quoteDate, Validators.required],
quoteItems: this.fb.array([])
});
this.addQuoteV2Item();
}
get quoteItems() {
return this.quoteForm.get('quoteItems') as FormArray;
}
quoteLineItems(index) {
return (this.quoteForm.get('quoteItems') as FormArray).at(index).get('quoteLineItems') as FormArray
}
addQuoteItem() {
this.quoteItems.push(this.fb.group({
description: '',
quoteLineItems: this.fb.array([])
}));
}
addQuoteLineItem(index, description) {
this.quoteLineItems(index).push(
this.fb.group({
rate: '',
quantity: '',
total: 0
})
)
}
您需要的是返回可观察值的方法
valueChanges
,因此您需要订阅它
ngOnInit(){
此.quoteForm.valueChanges.subscribe(inputField=>{
if(输入字段速率){
//对汇率做点什么
}else if(inputField.quantity){
//用数量值做点什么
}
});
}
我就是这样解决的:
updateTotal() {
var subtotal = 0;
var numberOfQuoteItems = (this.quoteForm.get('quoteItems') as FormArray).length;
for (let i = 0; i < numberOfQuoteItems; i++) {
var numberOfQuoteLineItems = ((this.quoteForm.get('quoteItems') as FormArray).at(i).get('quoteLineItems') as FormArray).length;
for (let j = 0; j < numberOfQuoteLineItems; j++) {
var currentLineItem = ((this.quoteForm.get('quoteItems') as FormArray).at(i).get('quoteLineItems') as FormArray).at(j);
subtotal = subtotal + currentLineItem.value.rate * currentLineItem.value.quantity;
}
}
this.subtotal = subtotal;
}
updateTotal(){
var小计=0;
var numberOfQuoteItems=(this.quoteForm.get('quoteItems')作为FormArray);
for(设i=0;i
如何获取嵌套的数量和费率字段?@RobbieMills如果我没有弄错,这个.quoteForm.quoteDate.quoteItems[0]quoteLineItems[0]费率
返回8
。如果需要动态值,则需要遍历每个数组(在我的示例中,我刚刚使用了[0]
作为第一个值)。现在您可以使用for
或forEach
来实现这一点。好的,问题是我不能在FormArray上使用forEach(不是函数错误),这就是我需要做的