#
Pass data to a child component in Angular
This tutorial will explain to you how to pass or send data to the child component in Angular 4.
Creating a child component in Angular is the same thing as creating a component in Angular. All components you create are part of another component so, you can name them a "child component". But not all the components are "parent". If you place the X component into Y component, Y is the parent and X is the child.
For this example, you have to create a new application in Angular and create a child component into an Angular application.
In my example, app Component is the parent Component and child1 Component is the child Component.
Pay attention to the following files:
<!--This is app.component.html file -->
<div style="text-align:center">
<h1 class="child">
Welcome to !
</h1>
<app-child1 [childvariable]="parentVariable"></app-child1>
</div>
/* This is child1.component.css file */
.child {
background-color: rgb(223, 247, 221);
}
/* This is child1.component.ts file */
import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core';
@Component({
selector: 'app-child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
@Input() childVariable: string;
constructor() { }
ngOnInit() {
}
}
<!--This is child1.component.html file -->
<div>
child1 works!
<br>
<div class="child">
Attention:
</div>
</div>
/* This is app.component.ts file */
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
parentVariable: string = "The variable is set in Parent Component, but is seen in the Child Component."
}
Pay attention to the way each file type can be commented !
What you have to retain is:
- in the parent view you have
[childVariable]="parentVariable"
- the
parentVariable
is defined in the parent ts file - in the child Component the variable is defined by
@Input() childVariable: string