Passing Data Between Parent/Child Components
Let’s look at ways in which parent and child components pass data between each other.
We'll cover the following...
There are different ways to pass data in and out of components. Choosing which approach to take depends on the complexity of the application you are developing and the relationship between the components.
The first approach we’re going to look at is the parent/child relationship, where one component has a child component.
Passing data from the parent component to the child component
Using @Input()
decorator
The flow of data in this instance is from the parent to the child. We use the @Input()
decorator to pass data from the parent to the child component via the template of the child component.
Parent component
For example, look at the following parent component:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent-comp',
template: `<app-child-comp [messageForChild]="parentMessage"></app-child-comp>`,
styleUrls: ['./parent-comp.component.scss']
})
export class ParentCompComponent {
parentMessage = "Tidy your room";
constructor() { }
}
Here, we are using an inline template, which has the child component’s tag passing the parentMessage
property to the child component via the messageForChild
property.
Child component
Let’s look at the child component. In this example code you can see that we’ve set the @Input()
decorator on the messageForChild
property. Now, this property is recognized by Angular as a way to pass properties into the child component.
📝 Note: Press the RUN button to ...