For real this a real quick one. But this does bring up a pretty crucial topic along the way, change detection. This will touch on CD a little but a another post will be dedicated to outlining CD more fully.
I have a hierarchy. How do I pass the state (data) I have in my parent component to the child components making up the whole? Use @Input().
So the concept is pretty straight forward. The top level parent owns all the data. The child components are passed the data. When implemented correctly, the child components do not change the data given to them. This is a term called immutability. Immutability in component state keeps our local app state in sync. If only the parent component can change state and do so in a manner that keeps our data immutable (unchangeable), the Angular can quickly and efficiently push state changes to all the components that consume the same state.
Immutability can be a deep subject, but what is important to take away is our parent component holds state. It gives state to the child through the @Input. If the child needs to change state, it emits an event that the parent can listen to. The parent handles the event with the parameters given to it from the child EventEmitter and can make changes to the immutable state. Then Angular change detection handles pushing the new state to all the child component @Inputs. How to makes changes to immutable state is another topic. Read more on that from Victor Savkin.
Asynchronous data throws a wrench in our system. When the parent component is being built by Angular at render time it does not have the data back from the server to bind to the inputs of the child components. The parent component will send an undefined input value to the child. But when the data does come back from the server we need to make sure that data is given to the child components. This is change detection. What the components do when a change in state is detected?
In AngularJS this was handled by dirty checking. It was like a file watcher looking for changes. This was simple for implementation, but not performant. Instead Angular changed the CD architecture to a push approach like React. This means components need to be more explicit in stating how they are going to handle state changes.
So how do we update child component input values if not using immutable objects? We get a life-cycle function, ngOnChanges. This gives us an object we can use to set the value of the child state.
Or we can use Inputs with get and set methods that call when a component input changes.
But if you are use immutable data structures or observables (observables are immutable by nature of returning new object on .next ), you can optimize your change detection performance with ChangeDetectionStrategy.OnPush.
But at their simplest, @Inputs get state down to the child components. This opens the door for Angular’s new Change Detection engine.