Sending data from a parent component to a child component in Angular
As indicated in this article, it is common to share data between a parent component, and one or more child components. One can implement this pattern by using @Input()
and @Output()
directives.
However, the explanation for this pattern is NOT very clear. Here in this series of articles, I would like to explain the implementation of this pattern in detail. First, I’ll explain @Input()
.
For demonstration, first create a blank Angular project. Delete all content in app.component.html
.
Sending data to child components
Use the app-root
as the parent component. In app.component.ts
, write the following code:
import { Component } from '@angular/core';@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentItem = 'Television';
}
Note that I add a data member currentItem
whose value is Television
. This is the data that will be passed to a child component.
Use angular-cli
to generate a component, say child. See the following code.
import { Component, OnInit, Input } from '@angular/core';@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit { @Input() item!: string; constructor() { } ngOnInit(): void {
}}
Note that Input
is imported in the first line. A data member item
is added and is decorated with a directive @Input()
. You should notice that a !
is appended to item
variable. !
is the definite assignment assertion operator, which tells you will initialize hte item
through means other than the constructor (for more informtation here, find for definite assignment assertion operator). Here, the item
will be initialized by the parent component not by the constructor.
<app-child [item]="currentItem"></app-child>
Here, the attribute [item]="currentItem"
has to be explained in detail. In the left-hand side of =
, the item
, which is surrounded by a pair of square brackets, is the data member item
of the child component (whose name is app-child
here). In the right-hand side =
, the currentItem
, which is surrounded by double quotation marks, is the data member currentItem
of the parent component (which is the app-root component here).
In summary, to send data from a parent component to a child component, follow these steps.
- Put the data in the parent component, of course.
- Add a data member with a definite assignment assertion operator in the child component.
- Decorate the data member in the child component with
@Input()
. - In the parent component’s HTML markup, add the child component tag.
- In the child component tag, add an attribute to assign the value of the data member in the parent component to the child component’s corresponding data member.