如何通过输入()将对象传递给子组件,但在父母更改时切勿更新输入



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

通过输入((传递对象的最佳方法是什么?

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

 @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));
     }
 }

如您提到的:当我们使用@input((传递对象时,它将作为参考传递,当我们通过原始类型时,它将作为值传递。

因此,我认为一种解决方案是将您的对象转换为字符串,然后使用@input((传递它。稍后,您可以根据需要将此串曲的对象解码为对象。

最新更新