Here is an example showcasing the interaction between parent and child components in Angular.
- Parent to child binding is achieved through property binding, where a master string is passed to the child component using a custom property called childToMaster with @Input decorator.
- Child to parent binding is implemented via event binding using @Output decorator. Look for the childToMaster event.
See the working demo here
Parent Component:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
// Passing values from parent to child
master: string = "sent from parent";
// Receiving value from child
childToParent(name) {
this.master = name;
}
}
Parent Template:
<div>
<span>Master to Child </span><input type="text" [(ngModel)]='master'>
</div>
<app-child [childToMaster]=master (childToParent)="childToParent($event)"></app-child>
Child Component with Template:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<input type="text" [(ngModel)]='masterName'>
<button (click)="sendToParent(masterName)">Send to Parent</button>
<div>{{masterName}}</div>
`
})
export class AppChildComponent {
// Receiving value from parent to child
@Input('childToMaster') masterName: string;
@Output() childToParent = new EventEmitter<String>();
sendToParent(name) {
this.childToParent.emit(name);
}
}