There are several ways to pass data/variables from a parent component to a child component in Angular. Two of the most common method are:
- Using @Input decorator
- Using shared service
1. Using @Input decorator
One way is to use the @Input() decorator to declare a variable in the child component that will receive the data from the parent.
In the parent component’s template, use the property binding syntax (square brackets) to bind the value of a variable to the input of the child component.
For example, in the parent component’s template:
<!--parent.component.html-->
<app-child [inputFromParent]="data"></app-child>
In the child component’s class:
// child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<p>{{ inputFromParent }}</p>
`
})
export class ChildComponent {
@Input() inputFromParent: any;
}
2. Using shared service
Another way is to use a shared service. A shared service is a way to share data between components that are not directly related.
In the parent component’s class:
// parent.component.ts
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
`
})
export class ParentComponent {
constructor(private dataService: DataService) {
this.dataService.data = 'Hello from the parent component!';
}
}
In the child component’s class:
// child.component.ts
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-child',
template: `
<p>{{ data }}</p>
`
})
export class ChildComponent {
data: any;
constructor(private dataService: DataService) {
this.data = this.dataService.data;
}
}
There can be other ways to pass variables from a parent component to a child component in Angular. These are just two of the basic approaches.