Output

Using the @Output decorator we can create custom events to communication with parent component

Create custom event

import {Output} from '@angular/core';

@Component({
    selector: 'app-counter',
    template: `
    <p> Count: {{ count }}</p>
    <button (click)="increment()">Increment</button>
})
export class CounterComponent {
    @Input() count = 0;
    @Output() countChange = new EventEmitter();

    increment()
    {
        this.counter++;
        this.countChange.emit(this.count);
    }
}

Using custom event

Parent component can listen to child custom event with the same syntax as DOM event

@Component({
    selector: 'app-root',
    template: `
    <p>Parent count: {{ parentCount }}</p>
    <app-counter (countChange)="onCountChange($event)"></app-counter> 
    `
})
export class FavoriteComponent {
    parentCount: number;
    onCountChange(count: number){
        this.parentCount = count;
    }
}

Last updated

Was this helpful?