我有一个显示项目(对象)列表的组件。我想创建另一个接收此列表作为其模型(或作为参数)的组件,并创建一个包含此数据的仪表板。例如,我有一个产品清单,包括每个单位的数量和价格,并希望在子组件上显示总价格。
通过创建组件并将列表传递给子项,可以正确显示总价格,但是,当新项目添加到列表中,或者当项目的数量/价格在列表中更改时,我的子组件不会被触发,也不会自我更新。
我已尝试使用ControlValueAccessor
和OnChanges
父母代码
<result [(ngModel)]="productList" [test]="armorList"></result>
关于孩子的代码 - 我知道使用模型和输入可能不正确,我只是尝试了两者,确定哪个更好。
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 {
}
}
由于
答案 0 :(得分:0)
Angular通过引用(而不是值)检测数组和对象中的更改。由于您刚刚向数组添加了一个项目,因此它的引用仍然保持不变。
因此,要检测数组中的更改,您需要采用以下任一策略。