Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular @Input of type Observable

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

like image 869
Ivelin Matev Avatar asked Jul 20 '18 10:07

Ivelin Matev


2 Answers

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.

like image 121
Silvan Bregy Avatar answered Oct 11 '22 04:10

Silvan Bregy


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.

like image 38
Tomas Avatar answered Oct 11 '22 05:10

Tomas