Building on the previous blog post, we now want to pass data from the parent component to the child component. Using our example from last time, we now add the data that we want to pass:

Parent Component

parent.component.ts

import { Component, ViewChild } from '@angular/core';
import ChildComponent from '../childComponent/child.component';

@Component({
  selector: 'app-parent-component',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
})

export class ParentComponent {
    @ViewChild(ChildComponent) childComponent: ChildComponent
    public userData: any[] = [
        {
            id: 345,
            name: "Ahmad Adam",
            email: "[email protected]",
            enabled: true
        },
        {
            id: 1423,
            name: "Anisa Adeel",
            email: "[email protected]",
            enabled: true
        },
        {
            id: 1745,
            name: "Samir Rifai",
            email: "[email protected]",
            enabled: false
        },
    ];
}

NOTE: Since this is a simple example, we will bypass Typescript’s type checking system by using the any data type. When working on actual application, we would either state the data type using one of Typescript’s built-in data types (e.g. number, string, boolean, etc.) or create an interface or type as a model for our data.

We then proceed by adding the data that we want to pass to the child component. We add data in between the square brackets. This will be the name of the variable that will receive the user data in the child component and then set it so that the value of the variable userData will be passed to it.

<ng-template>
    <app-child [data]="userData"></app-child>
</ng-template>

Child Component

We now need to receive the value of the data in the child component. We receive the data from the parent component using @Input like so:

child.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child-component',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
})

export class ChildComponent {
@Input() data: any[];

}

child.component.html

<ul>
    <li *ngFor="let datum of data">
        {{ datum.name }} {{ datum.email }}
    </li>
</ul>