Search code examples
angularinputnestedcomponentsparent-child

Angular using @Input for deeply nested components


I am new to Angular and try to understand the best way to solve the following scenario (also see link with an illustration):

I got a page with multiple tiles (like mat-cards). Each tile has a couple of functionalities like showing a chart, a table and some actions around it.

illustration of my nested components in angular

I could nest components and pass the data from the parent (who gets data from a service) down to the n-th grand-child. So something like parent > @Input child > @Input grand-child > @Input n-th grand child. But is this the right approach or are there downsides of ‘chaining’ data by @Input variables beyond a child component (e.g. grand-grand-children)? I am asking as I only see examples of a simple parent-to-child @Input interaction but couldn’t see any example / recommendation that you would do this to deeply nested (grand-) children as well. Thank you for you recommendations.


Solution

  • Yes. Unfortunately, if you're deadset on using @Input(), you would have to do it this way.

    Alternatively, you could consider using observables or the ngrx store for this purpose depending on the data you're passing down.

    It sounds like you may be passing table data from the parent component down to the grandchild. In this case, I would recommend subscribing to that data from the grandchild via an observable.

    This would clean up all those @Input()'s you may need and you may not even need to refer to them in the parent component if this data is stored in a service.

    Check out this answer for how you might do that.