首页 > 解决方案 > 如何通过 Inputs() 将对象传递给子组件,但在父组件中更改时从不更新输入

问题描述

我通过 Inputs() 将一个对象从父组件传递给子组件。我知道是因为我传递的是一个对象而不是原始类型,它传递的是对该对象的引用。因此,当对象在父对象中发生变化时,我会看到它反映在子对象中。

通过 Inputs() 传递对象的最佳方法是什么,当它在父组件中发生更改时不会更新子组件?

标签: node.jsangulartypescript

解决方案


您需要使用两个属性。一个是您修改的,另一个是传递给子组件但是原始组件的克隆。

 @Component({..})
 export class MyComponent implements OnInit {
     // the original object value
     public value: any;
     // a value used by child components
     public forChild: any;

     public OnInit() {
         // use deconstruction to make a copy
         this.forChild = {...this.value};
         // use assign to make a copy
         this.forChild = Object.assign({}, this.value);
         // use JSON to make a deep copy
         this.forChild = JSON.parse(JSON.stringify(this.value));
     }
 }

推荐阅读