abhilash reddy
abhilash reddy

Reputation: 1586

How to pass an object from parent component to children components in angular2?

Say i have 3 Angular components and first component uses the second and third component as a directive. They should share the same model object, which is initialized in the first component. How can I pass that model to the second and third component? I referred this post How to pass object from one component to another in Angular 2? but it is using inputs... I want to know all the possible alternatives to share the model object between various child components Somebody please tell me the alternatives which i can follow

Upvotes: 0

Views: 1071

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364727

An advantage of using input properties on the children (rather than a shared service) is that Angular change detection will automatically propagate changes to the children. This is especially useful if you are using immutable objects and you want to change your entire model (to a new instance/reference).

With a service, you can change the model, but not the model reference.

With input properties, you can do either: change the model and/or change the model reference.

See the following Savkin blog post for more about modeling using immutable data: http://victorsavkin.com/post/133936129316/angular-immutability-and-encapsulation

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658027

Add the type to the providers list of the First component and inject it into the constructor of First, the involved child, and grandchild constuctors.

@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.
}

Don't add SharedService to any of those child or grand-childrens providers or they'll get a new instance instead of the shared instance.

If you add SharedService to bootstrap(AppComponent, [SharedService]) instead of the parent component, the whole application shares the seam SharedService instance instead of just a selected subtree.

Upvotes: 1

Related Questions