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

查看:33
本文介绍了如果@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.

如果我尝试使用 setter,它也不起作用:

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() 变量,所以像这样传递

for eg. someVar = {key: value} this is @Input() variable, so pass like

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

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

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

如果扩展运算符不起作用,请使用任何对象深度复制方法,例如

if spread operator won't work use any object deep copying methods like

JSON.parse(JSON.stringify(obj))

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

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