Angular如何通过以下方式检测父级到子级的变化



示例组件有数据对象数组,并且在其数组循环中有子组件。Sample.component

export class SampleComponent implements OnInit {
data = [{ value: 3 }, { value: 1 }];
constructor() {}
ngOnInit(): void {}
valueChange() {
this.data[1].value = 5;
this.data = [...this.data];
}
whenComponentRerendered() {
console.log('Parent component rerendered');
}
consoleOutput() {
console.log('Console from button click');
}
}
<button (click)="valueChange()">
Change input to 5
</button>
<ng-container *ngFor="let item of data">
<app-samplechild [data]="item"></app-samplechild>
</ng-container>

现在我需要检测当对象上的任何值从父

改变时的变化
export class SamplechildComponent implements OnInit {
@Input('data') data!: any;
constructor() {}
ngOnInit(): void {}
whenComponentRerendered() {
console.log('child component rerendered');
}
changeValue() {
this.data.value = 5;
}
}
<p>
The value from parent is
{{ data | json }}
</p>

我无法获得更改,因为数据不是输入值。如何让孩子改变?StackBlitz注意:这只是示例代码,在实际数据中有大量具有多个层次结构的对象数组。

changeDetection: ChangeDetectionStrategy.OnPushSamplechildComponent中移除。那就没问题了。你应该使用默认的角度changeDetection系统。

相关内容

最新更新