Want your components to share information? Yes, they can!
Say you have two components, a parent component (PC) and a child component (CC) and you want the data to move from the parent component to the child component or vice versa, you use COMPONENT COMMUNICATION/INTERACTION.
There are multiple ways to achieve that. This article focuses on the use of @Input() to receive the data from the PC to CC.
@Input decorator is used to pass data from parent to child component. Now suppose we have created two components:
app.component.ts and child.component.ts
Here, we have decorated the message property with the @Input() decorator so that value of the message property can be set from the parent component.
https://gist.github.com/NishuGoel/d9d60bffd9ad81c004e24a1d7055a0fe
Now, let us modify the parent component AppComponent to pass data to the child component.
https://gist.github.com/NishuGoel/f4381fbb870074df00b09cc6957b3252
We create a property called _message and using @Input() decorator, create getter and setter for the _message property.
It checks here if the value passed is an empty string. If yes, we assign the default value for message in the child component.
This is one-way communication between components. In the upcoming article, we’ll see component communication both ways.
Reblogged this on Nishu Goel.