How to pass data from parent to child and vice versa in Angular?
In Angular, data can be passed between a parent component and its child component in several ways.
- Input binding: You can use the
@Input
decorator to pass data from a parent component to its child component. The@Input
decorator allows you to bind a property of the child component to a value that is passed in from the parent component’s template.
Here’s an example of how to pass data from the parent to the child component:
// child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
{{ message }}
`,
})
export class ChildComponent {
@Input() message: string;
}
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child [message]="message"></app-child>
`,
})
export class ParentComponent {
message = 'Hello from the parent!';
}
- Output binding: You can use the
@Output
andEventEmitter
to pass data from a child component to its parent component. The@Output
decorator allows you to bind a property of the child component to an event that can be emitted from the child component. The parent component can subscribe to the event using the(event)
syntax in the template.
Here’s an example of how to pass data from the child to the parent component:
// child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from the child!');
}
}
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
})
export class ParentComponent {
receiveMessage(message: string) {
console.log(message);
}
}
These are the two most common ways to pass data between a parent component and its child component in Angular.