如何将对象从父组件传递给angular2中的子组件?

时间:2016-02-02 05:59:13

标签: angular

假设我有3个Angular组件,第一个组件使用第二个和第三个组件作为指令。它们应该共享相同的模型对象,该对象在第一个组件中初始化。如何将该模型传递给第二和第三个组件?我引用了这篇文章How to pass object from one component to another in Angular 2?,但它正在使用输入...我想知道在各种子组件之间共享模型对象的所有可能的替代方法 有人请告诉我可以遵循的替代方案

2 个答案:

答案 0 :(得分:1)

将类型添加到First组件的提供者列表中,并将其注入@Component({ ... providers: [SharedService] }) export class First { constructor(private shared: SharedService); // also add this parameter to the other child and grand-child // component and directives constructors and they will get // passed a shared instance. } 的构造函数,涉及的子项和孙项构造器。

SharedService

不要将providers添加到任何子项或子项SharedService中,否则他们将获得新实例而不是共享实例。

如果将bootstrap(AppComponent, [SharedService])添加到SharedService而不是父组件,则整个应用程序将共享seam {{1}}实例,而不仅仅是选定的子树。

答案 1 :(得分:0)

在子项(而不是共享服务)上使用输入属性的一个优点是Angular更改检测会自动将更改传播到子项。如果您使用不可变对象并且想要更改整个模型(到新实例/引用),这将非常有用。

使用服务,您可以更改模型,但不能更改模型参考。

使用输入属性,您可以执行以下任一操作:更改模型和/或更改模型参考。

有关使用不可变数据建模​​的更多信息,请参阅以下Savkin博文:http://victorsavkin.com/post/133936129316/angular-immutability-and-encapsulation

相关问题