【问题标题】:why is child not detecting change from parent input in angular为什么孩子没有检测到来自父母输入的角度变化
【发布时间】:2018-11-25 03:20:50
【问题描述】:

我有一个子组件

parent.component.html

 <child-component (changeVal) = "parentObj"></child-component>

parent.component.ts

parentObj = {
  someDate = new Date()
}
// function changing the parentObj
callOnClick() {
   this.parentObj.someDate = new Date('20 June 2018'); 
}

子组件.ts

@Input('changeVal')
ngOnChanges() {
 // console i never see
 console.log('parentObj Changed and got me here');
}

为什么在这种情况下 onChanges 钩子没有运行?我正在更改 callOnClick 方法中的输入值,当 changeVal 的值更改时它不应该触发吗?

【问题讨论】:

  • 感谢拉维的简单解决方案。荣誉!

标签: angular


【解决方案1】:
<child-component (changeVal) = "parentObj"></child-component>

changeVal 是代码中的输入,但 HTML 中的输出。考虑改用这个:

<child-component [changeVal] = "parentObj"></child-component>

并声明一个变量作为输入,而不是你的函数。

@Input() changeVal: any;

【讨论】:

  • 仍然看不到控制台消息。
  • 在你的装饰器后面声明一个变量,函数不输入,尤其是生命周期函数
【解决方案2】:

如果我没记错的话,您是在尝试将对象从父级传递给子级。

parentObj 是一个属性。使用方括号使用属性绑定,如下所示:

<child-component [changeVal] = "parentObj"></child-component>

此外,在 child.component.ts 中,您必须将 @Input() 装饰器提供给属性而不是方法。

    @Input('changeVal') changeVal = {};
    ngOnChanges() {
      // console i never see
      console.log('parentObj Changed and got me here');
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2020-04-11
    • 1970-01-01
    相关资源
    最近更新 更多