【问题标题】:Why can you access angular ngOnChanges SimpleChange property directly from SimpleChange object without using index为什么可以直接从 SimpleChange 对象访问角度 ngOnChanges SimpleChange 属性而不使用索引
【发布时间】:2022-01-18 00:05:15
【问题描述】:

我正在使用 ngOnChanges,并且我已将 SimpleChange 参数设置如下。为什么我可以使用 changes.currentValue 直接访问我的输入属性,而不必使用索引获取属性?两者都有效,我很困惑为什么?

  ngOnChanges(changes: SimpleChange) {
    console.log('ngOnChanges called with changes value: ', changes.currentValue) // why does this work? is it because by convention it works if I have just one input property??
   
    for (const propName in changes) {
      console.log('ngOnChanges called with propName value: ', changes[propName].currentValue)
    }
  }

【问题讨论】:

    标签: angular ngonchanges


    【解决方案1】:

    您使用SimpleChange 类型声明changes 参数,但根据docs,它们应该是SimpleChanges 类型(注意末尾的's');

    ngOnChanges(changes: SimpleChanges): void {
        console.log(changes['YOUR_PROP'].currentValue);
    }
    

    【讨论】:

    • 啊啊啊!这是一个错字,但这让我想知道为什么如果它只是一个对象,为什么仍然能够在更改参数上使用 for 循环?当我在 for 循环中更改 [propName] 时,我仍然可以获得完整的对象并且可以访问它的键。
    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多