In this article, we will learn how to pass data from parent component to child component using @Input() in Angular 9.
@Input() allow Angular to share data between the parent context and child directives or components. An @Input() property is writable.
Use the @Input() decorator in a child component to let Angular know that a property in that component can receive its value from its parent component. It helps to remember that the data flow is from the perspective of the child component. So an @Input() allows data to be input into the child component from the parent component.
Prerequisites:
- Basic knowledge of Angular
- Code editor like Visual Studio Code
Create a new Angular project by typing the following command in the VSCode terminal.
ng new parent-to-child
Now, open the newly created project and execute the commands given below. It will create two components parent and child.
ng g c parent ng g c child
Open the parent.component.ts file and add the code in it.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { preText = 'Hello'; list = [ { id: 1, name: 'John' }, { id: 2, name: 'Mark' }, { id: 3, name: 'Deo' } ]; constructor() { } ngOnInit(): void { } }
Open the parent.component.html file and add the code in it.
<h1>{{list.length}} Names:</h1> <app-child *ngFor="let result of list" [data]="result" [preText]="preText"> </app-child>
Open the child.component.ts file and add the code in it.
import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() data: any; @Input('preText') pre: string; constructor() { } ngOnInit(): void { } }
Open the child.component.html file and add the code in it.
<h3>{{pre}}, {{data.name}}</h3>
Open the app-routing.module.ts file and add the code in it.
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ParentComponent } from './parent/parent.component'; import { ChildComponent } from './child/child.component'; const routes: Routes = [ { path: 'parent', component: ParentComponent, }, { path: 'child', component: ChildComponent, } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Open the app.component.html file and add the code in it.
<router-outlet></router-outlet>
Output:
Please give your valuable feedback and if you have any questions or issues about this article, please let me know.
Also, check Dynamic Page Title Based On Route In Angular 9