[英]Angular how to detect changes from parent to child in the following way
Sample Component has data which array of object and it has child component on their array loop.示例组件的数据为 object 数组,并且其数组循环中有子组件。 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>
now I need to detect changes when any value on object is changed from parent现在我需要检测 object 上的任何值从父级更改时的更改
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>
I couldn't get the changes since the data is not an Input value.我无法获得更改,因为数据不是输入值。 How to get changes in child?
如何获得孩子的变化? StackBlitz Note: This is only sample code, in realistic data has huge number arrays of object with multiple hierarchy.
StackBlitz注意:这只是示例代码,在现实数据中有大量 arrays 的 object 具有多个层次结构。
Remove changeDetection: ChangeDetectionStrategy.OnPush
from SamplechildComponent
.从 SamplechildComponent 中移除
changeDetection: ChangeDetectionStrategy.OnPush
SamplechildComponent
。 Then it works fine.然后它工作正常。 You should use default angular
changeDetection
system.您应该使用默认的 angular
changeDetection
系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.