Communicating with parent component from child component in Angular Js2

In my last blog I have explained about @Input decorator to pass data from parent component to the child component. @Output is on other hand used in response to some event within a child component to receive some information for the parent component through some events. If you are not read my previous blog , I would suggest you to read the same. I have used the same example here also.

Child Component
Let’s talk about the child component first. You can see I have a simple method named productCardClick() which I am calling when clicking on the button. It’s pretty straight forward.

Modifying the child component
Next I am going to pass some data to the parent through the same productCardClick() method in the child component. In order to do that first you have to add a new property of type EventEmitter and emit the data you want to pass in to the parent component through this property like below .

Parent Component
Let’s go the parent component named ProductListComponent


In the parent component (ProductListComponent) you can see I have receiver method named onProductCardClickHandled(data:any) with a parameter to receive the data from the child component and I am calling this receiver method with a parameter via the @Output decorated property onProductCardClick inside the child component. Now when you click the button you will receive the child component data in to the parent component

Communicating with child components from parent component in Angular Js2

Breaking our application in to multiple components makes our application more organized and maintainable. Here I am going to explain how to pass data from parent component to child component.

Parent Component
Here is our ProductListComponent , which is the parent component with a productObject declared which I am going to pass in to the child component.

This is my productList html for displaying the product object. You can see I am calling the product-card component(Child Component) from this productListComponent

Child Component

Child Component template

In this component I have declared a variable named product decorated with @Input , which tell to the child component that , you will get an input product from the parent component(ProductListComponent). For passing the input data from the parent component to the child component you have to add an attribute match with property decorated with the @Input inside a square bracket like below and the value here I am passing will be the productObject from the ProductListComponent

Typescript Error : duplicate string index signature angular 2

I got this error after installing the jQuery typings .The error is because of you have installed the definition files into multiple locations in your project. Both globally and locally. For get rid of this error you have to remove either of this definition files from your prooject.

npm remove @types/jquery –save-dev

Hope this helps