In that case we used reference to method as props to child component
- Let's create a Parent component first
Here you have to notice few points
First you will create a parent component with constructor
Within the constructor you set a state called parentName with value Parent
Next define a method greetParent() which alert hello with the parentName initialized.
In the constructor you will assign this.greetParent to this.greetparent.bind(this)
Now you will create child.component.ts
We are not using state here therefore we can use a simpler component here.
- Here you will just add a button "Greet Parent"
- Back in parent component , you will include child component in render method .Make sure to import component at top.
- You will render parent component in app.js
After running you will see
But nothing will happen if you click the button.
- In ParentComponent render method you are going to add child attribute named greetHandler. And to this we assign greetParent().
- In child component on click of button we call props.greetHandler.
- When you click button you will see alert like this
Now we will see _how to pass a parameter when calling a parent method from child component and this is where an arrow function in the return statement is really useful_
Array function syntax is the simplest way to pass parameters from child component to parent component.
This is how you will change your child component to achieve this
- In parent component you will receive props like this and change alert method
After this you will see the message like this while clicking on send button.
Top comments (0)