0

I have 18 directives all picking apart a very large Object that the parent component is subscribed to (not http). Do I dole out the properties to the different directives or would it be better instead to pass the observable and let the varying components subscribe to only the properties they need.

In short, should I:

  1. Pass an observable to angular2 directives and subscribe from within the directive component

  2. Subscribe in the parent and pass the resulting data of observable to angular2 directives. (This is how I currently have it implemented)

1 Answer 1

2

With Angular2 and component tree structure comes a pattern that you should use : Dumb and Smart components.

  • A Smart component can register to anything you want and have some logic in it
  • A Dumb component on the opposite is supposed to be used only to display a view with some data (passed as Input)

A really simple example would be :

PersonComponent : A dumb component should display a person (let say name and age)

  <div>
    Hi, my name is {{person.name}} and I'm {{person.age}} years old !
  </div>

PeopleComponent : A smart component which calls PeopleService to get a list of user. It then subscribe to the response (which is an Observable). His view should display the list of person like that :

  <person *ngFor="let p of people" [person]="p"></person>

And let say that you don't even really need to subscribe to your observable within your TS file, then you could use the async pipe from Angular2 :

<person *ngFor="let p of (people | async)" [person]="p"></person>

The important thing is that PersonComponent will not receive (neither in the first nor the second solution) an Observable. It's just a dumb component which has to display data when needed (when the observable receive at least one response from the server).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.