7

Is it bad practice to pass in a component's @Input an observable ?

For example: The template of the parent will have

<profile-edit [items$]="profileFacade.items$">

and the ProfileEditComponent will have a variable like this:

@Input items$: Observable<ProfileItem[]>

And use the | async pipe to unrwap the values of the observable in the template of the ProfileEditComponent

2
  • Thanks @Tomas. Edited... Commented Dec 10, 2018 at 17:33
  • Be care with Observables as @Input, as they trigger ngOnChanges a lot. Use with care Commented Oct 26, 2020 at 21:03

2 Answers 2

5

I think this is not good practice. Angular provides you an async pipe which is exactly what you want here.

When using async pipe:

  • less code is generated since you do not need to subscribe to the observable first.

  • The component does not need to know about Observable class and is more stupid like this

So I think this:

<profile-edit [items]="profileFacade.items$ | async">


@Input items: ProfileItem[]

Is cleaner and better than this:

<profile-edit [items]="profileFacade.items$">`


@Input items: Observable<ProfileItem[]>`

Just my guesses, I am not a specialist.

Sign up to request clarification or add additional context in comments.

1 Comment

I disagree. Observable input is not bad practice. Moreover, It allows to set the changeDetectionStrattegy to OnPush, which will result in an optimized component, and no OnChanges interface has to be implemented to handle changes.
2

For async pipe this is good solution, but be aware of change detection mechanism. Because from angular point of view [items] bounded property does not change, if your change detection strategy will be set to onPush, your view might not be refreshed accordingly. Then, you will need to manually subscribe to this input observable and on each change trigger change detection by yourself.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.