[英]Use array of objects as model on child angular component and watch for changes
I have a component that displays a list of items (objects). 我有一个显示项目(对象)列表的组件。 I want to create another component that receives this list as its model (or as a parameter) and creates a dashboard with this data.
我想创建另一个组件,以将该列表作为其模型(或作为参数)接收并使用此数据创建仪表板。 For example, I have a list of products, with quantity and price per unit, and want to display on the child component the total price.
例如,我有一个产品列表,其中包含数量和单价,并希望在子组件上显示总价。
By creating the component and passing the list to the child the total price is displayed correctly, however, when new items are added to the list, or when the quantity/price of an item is changed inside the list, my child component does not get triggered and does not updates it self. 通过创建组件并将列表传递给子组件,可以正确显示总价,但是,当将新项目添加到列表中时,或者在列表内更改了项目的数量/价格时,我的子组件无法得到触发并且不会自我更新。
I already tried to use ControlValueAccessor
and OnChanges
我已经尝试使用
ControlValueAccessor
和OnChanges
Code on parent 父代码
<result [(ngModel)]="productList" [test]="armorList"></result>
Code on child - I know that using model and input might not be correct, I just tried both , sot sure which would be better. 关于子代的代码-我知道使用模型和输入可能不正确,我只是尝试了两种,所以肯定会更好。
import { Component, Input, OnChanges, Output, EventEmitter, forwardRef, SimpleChanges } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { Armor, Material } from "../armor-list.component";
import * as _ from "lodash";
@Component({
selector: 'result',
templateUrl: './result.component.html',
styleUrls: ['./result.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ResultComponent),
multi: true
}
]
})
export class ResultComponent implements ControlValueAccessor, OnChanges {
@Input() test: Product[];
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
writeValue(obj: any): void {
if (obj !== undefined && obj !== null) {
//logic to calculate the price
}
}
registerOnChange(fn: any): void {
}
registerOnTouched(fn: any): void {
}
}
Thanks 谢谢
Angular detects changes in array and object by reference (not by value). Angular通过引用(而不是通过值)检测数组和对象的变化。 Since you have just added an item to array, its reference stills remain same.
由于您刚刚将项目添加到数组,因此其引用静止图像保持不变。
So to detect changes in array, you need to adopt either of the following strategies. 因此,要检测阵列中的更改,您需要采用以下两种策略之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.