A common pattern in Angular is sharing data between a parent component and one or more child components. To implement this pattern use the @Input() decorator.
Consider the following hierarchy:
<parent-component>
<child-component></child-component>
</parent-component>
The <parent-component> serves as the context for the <child-component>.
@Input() lets a parent component update data in the child component.
Parent to child component communication using @Input decorator
The @Input() decorator in a child component signifies that the property can receive its value from its parent component.
To use @Input(), you must configure the parent and child.
Configuring the child component:
To use the @Input() decorator in a child component class, first import Input and then decorate the property with @Input(), as in the following example.
import { Component, Input } from ‘@angular/core’;
export class ChildComponent{
@Input() childData:string = ”;
}
In this case, @Input() decorates the property childData, which has a type of string, however, @Input() properties can have any type, such as number, string, boolean, or object. The value for childData comes from the parent component.
Next, in the child component template, add the following:
<p>{{childData}}</p>
Configuring the parent component:
The next step is to bind the property in the parent component’s template. In this example, the parent component template is parent.component.html.
- In the parent component class, designate a value for parentData:
- Use the child’s selector, here <app-child>, as a directive within the parent component template.
Placing the child component in the parent component
- Use property binding to bind the childData property in the child to the parentData property of the parent.
<app-child [childData]=”parentData”></app-child>
More Pages
-
All in Edupoly
-
HTML Advanced Tutorial
-
Practice Coding Problems
-
Reference Links
-
Registration Page
-
Test books and Notes
-
Java Programming Questions
-
Job Postings
-
HTML Coding Projects and Practice Examples
-
Code Chanlleges
-
Demo Classes
-
Quizzes Test Your Self
-
Upcoming Batches
-
Interview Questions
-
Free Video Tutorials
-
Coding Example Programs
-
Video Courses
-
Mini Capstone Projects
-
Workhops
-
Corporate Trainings