Passing data in Angular is a crucial concept to understand when working with the framework. In this tutorial, we will discuss various ways to pass data in Angular, particularly focusing on the @Input and @Output decorators.
Firstly, let’s understand the difference between @Input and @Output decorators in Angular.
- @Input decorator is used to pass data from a parent component to a child component. It allows a parent component to bind values to properties on a child component.
- @Output decorator, on the other hand, is used to emit events from a child component to a parent component. It enables a child component to notify the parent component of changes or actions.
Now, let’s dive into the implementation of passing data using @Input decorator.
Step 1: Creating Child Component
Firstly, create a child component where you want to receive the data from the parent component. Here is an example of a basic child component that uses @Input decorator:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<h1>{{data}}</h1>'
})
export class ChildComponent {
@Input() data: string;
}
In the code above, we have created a child component with a single property data
that is decorated with the @Input decorator. This property will receive data passed from the parent component.
Step 2: Passing Data from Parent Component
Now, we need to pass data from the parent component to the child component. Here is an example of how to do this:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: '<app-child [data]="dataToSend"></app-child>'
})
export class ParentComponent {
dataToSend = 'Hello from parent!';
}
In the parent component, we have a property dataToSend
which we want to pass to the child component. By binding the property to the child component using square brackets [data]="dataToSend"
, we are passing the value of dataToSend
to the child component.
Step 3: Displaying Data in Child Component
Finally, in the child component template, we can now display the passed data using interpolation {{data}}
. The child component template will render the value of data
received from the parent component.
<h1>{{data}}</h1>
That’s it! You have successfully passed data from a parent component to a child component using the @Input decorator in Angular.
In Part 2 of this tutorial, we will explore how to pass data from a child component to a parent component using the @Output decorator. Stay tuned for the next part!
Happy coding!