如果@Input正在接收对象,则ngOnChanges不触发 [英] ngOnChanges not firing if an @Input is receiving an object

查看:144
本文介绍了如果@Input正在接收对象,则ngOnChanges不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

父组件模板:

<my-component [param]="whatever"></my-component>

父组件代码:

whatever = { value1: 0, value2: 1, value3: 'foo' };

子组件代码:

@Input() public param: any;

ngOnChanges() {
  console.log('Received input: ', param);
}

这不起作用.子组件不会注意到对whatever所做的任何更改,并且ngOnChanges不会触发.

This isn't working. Any change to whatever will be unnoticed by the child component and ngOnChanges won't fire.

如果我尝试使用二传手,它也不起作用:

It also doesn't work if I try to use a setter:

@Input() set param(value) {
  console.log(value);
}

而且如果我尝试在父组件中运行手动区域更新也无济于事.

And it doesn't help if I try to run a manual zone update in the parent component.

显然,@Input()仅能检测对象的结构何时发生变化,而不能检测其值.

Apparently @Input() can only detect when an object's structure has changed, but not its values.

那么我该如何将对象作为@Input()属性传递,并让子组件检测值的变化?

So how can I pass an object as an @Input() property and have the child component detect value changes?

推荐答案

@Input属性值更改时,将触发角度更改检测.

Angular change detection is triggered when the @Input property value changes.

因此,要在对象发生变化时触发更改检测,您可以 使用扩展运算符 作为输入来传递对象的副本.

So to trigger change detection in case of an object you could pass a copy of the object using spread operator as the input.

例如someVar = {key: value}这是@Input()变量,因此像

<app-sample [someVar]="{...someVar}" ></app-sample>

{...VARIABLE}<-这就是魔力

{...VARIABLE} <- here is the magic

这篇关于如果@Input正在接收对象,则ngOnChanges不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆