As we are already aware Angular follows component philosophy, it is component based, everything is a component. Components are the main way we build and specify elements and logic on the page. We define root component and then multiple child components to that root component and then grand child components to child components and this continues which builds a component hierarchy. So obviously in this components have to talk with each other to pass data or for notifications, there are 3 patterns of communication over here
- Parent to child
- Child to parent
- Communication between sibling components
1. Parent to Child
This can be achieved using the @Input, to define an input for a component, we use the @Input decorator.
For example, our component needs a counter argument to initialize the counter in child component
Now we will define the @Input counter in component as below
HTML of child component looks some thing like this
As you can we have child component which has counter as Input propert from parent component, this input initializes the child components internal counter and whenever user clicks on the button in the child component
2. Child to Parent
Now when the user clicks on the button on child component it increments the counter, this increments needs to be notified to the parent component this is where @Output comes in to the picture. To be able to use our Output, we need to import and bind a new instance of the EventEmitter to it. We have to call .emit() to emit an event to the parent. So in the above case we hook in the @Output childComponentNotification to the event onChildComponentNotification event function which has been defined in the parent component.. Here is the snippet.
HTML for app component of parent component display the incremented counter from child component.Incremented counter is been passed as event parameter.