How to pass data from one component to another in angular
In this tutorial, we are going to learn about component communication in angular with the help of examples.
@Input
Angular provides us @Input
decorator by using that we can pass data from parent component to
child component.
Let’s see an example
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './childcomponent.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() name: string;
}
In the above code first, we imported an Input
decorator from the @angular/core
package and added it
in front of name
property so that it can available to pass data from the parent component.
<div>
<h1>{{name}}</h1></div>
Passing data from a parent component
It’s time to pass data from the parent component.
<div>
<h1>Welcome to angular world</h1>
<app-child name="Gowtham"></app-child></div>
In the above code, we are passing data to a child component by using a property name = "gowtham"
.
Passing dynamic values
We can also pass dynamic values to a child component by wrapping the property with [ ]
square brackets.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myname = 'Gowtham';}
<div>
<h1>Welcome to angular world</h1>
<app-child [name]="myname"></app-child></div>
Listening to child component events from the parent
In our case, If we want to change name
, we need to emit a custom event from our child component. The parent component reacts to that custom event.
Inside our child component first, we are importing an Output
decorator and EventEmitter from the @angular/core
package.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './childcomponent.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() name: string;
@Output() changeName = new EventEmitter();
updateName() {
// emitting changeName custom event this.changeName.emit(); }
}
<div>
<h1>{{name}}</h1>
<button (click)="updateName()">Change Name</button></div>
Here we are emitting a custom event called changeName
, whenever someone clicks on a button
.
Inside our app component, we are listening for the changeName
event and invokes the onchangeName
method.
<div>
<h1>Welcome to angular world</h1>
<app-child [name]="myname" (changeName)="onchangeName()"></app-child></div>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myname = 'Gowtham';
onchangeName() { this.myname = 'Angular'; }}