Passing Data to Child Component in Angular
You can pass data from a parent component to a child component. This data will be placed in the child class properties. Let's see how this is done.
First, let's create properties in the child component class that will import data from the parent component:
class UserComponent {
public name: string = '';
public age: number = 0;
}
Now we need to declare that these properties will receive data from the outside. For this, a special decorator Input
is used. We import it into our child component:
import { Input } from '@angular/core';
Now let's apply this decorator to our properties:
class UserComponent {
@Input()
public name: string = '';
@Input()
public age: number = 0;
}
Let's add data output to the child component template file:
<p>{{ name }}</p>
<p>{{ age }}</p>
Now, in the parent template, when calling the child component tag, we will write attributes whose names will match the names of our child class properties. The values of these attributes will be included in the child class properties:
<user-data name="john" age="25"></user-data>