Passing Data from Child to Parent in Angular

Posted by

Angular Pass Data Child To Parent

How to Pass Data from Child to Parent Component in Angular

One of the key features of Angular is its ability to easily pass data between components. In many cases, you may want to pass data from a child component to its parent component. This can be achieved using a combination of Angular features, including Inputs, Outputs, and EventEmitters.

Using Inputs

Inputs allow you to pass data from a parent component to a child component. However, you can also use the @Input decorator to pass data from a child component to its parent component. Here’s how you can do it:


// child.component.ts
@Input() dataFromChild: string;

In the above example, we’ve created an input property in the child component called dataFromChild. We can then bind this property to a value in the parent component like this:


Using Outputs and EventEmitters

Another way to pass data from a child to a parent component is by using Outputs and EventEmitters. Here’s how you can do it:


// child.component.ts
@Output() dataToParent = new EventEmitter();

passDataToParent() {
this.dataToParent.emit("Data from child component");
}

In the above example, we’ve created an output property in the child component called dataToParent. We’ve also created a method called passDataToParent that emits the data using the EventEmitter. In the parent component, we can then listen for this event and handle the data like this:



// parent.component.ts
handleDataFromChild(data: string) {
console.log(data); // Output: Data from child component
}

By using these Angular features, you can easily pass data from a child component to its parent component. This can be helpful in many scenarios, such as form submissions, user interactions, and data manipulation.