💻 Tech
Components can interact with other components with @Input
and @Output
decorators. @Input
decorator defines the data that can be passed from a parent to a child component. In the code below, the parent uses [childData]
to identify the receiver of the data in the child component. On the other hand, @Output
decorator defines an EventEmitter that the child component can trigger via emit
method. The child component isn’t aware what the function does; the parent abstracts it from the child component and just tells it what function the (childEvent)
will trigger.
// Parent component ts file
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child [childData]="parentData" (childEvent)="parentFunction($event)"></app-child>
`
})
export class ParentComponent {
parentData = "Data from parent";
parentFunction(event) {
console.log('Received event from child: ', event);
}
}
// Child component ts file
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<p>{{ childData }}</p>
<button (click)="emitEvent()">Click me</button>
`
})
export class ChildComponent {
@Input() childData: string;
@Output() childEvent = new EventEmitter<string>();
emitEvent() {
this.childEvent.emit('Event from child');
}
}