If you want to pass data to a nested component you
have to use the @Import decorator. You can find this decorator at @angular/core
import { Input } from '@angular/core';
Now I show you how you can use this decorator.
In my example I want to pass a counter from a Shopping
List to a Shopping Basket Component
In the end, the shopping basket should look like this:
The Shopping Basket shows the number of items in an
array (Shopping List). Everytime we put an item in the basket we count the
items in the array
this.counter = this.selectedProducts.length
Now we have to pass the counter to the
ShoppingBasketComponent by using property binding
<app-shopping-basket [count]="counter"></app-shopping-basket>
After this we can use the input decorator at the child
component
export class ShoppingBasketComponent implements OnInit {
@Input() count: any
constructor() { }
ngOnInit() {
}
}
And we can use it in the HTML
<h2>{{count}}</h2>
Summary:
Passing data from a parent to a child component is
very easy. You only use property binding at the parent component and the input decorator
at the child component.
Comments
Post a Comment