import { Component, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-child', template: ` `, }) export class ChildComponent { @Output() nameEntered = new EventEmitter(); name: string; submitName() { this.nameEntered.emit(this.name); } }
import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `{{ greeting }}
`, }) export class ParentComponent { greeting: string; greetUser(name: string) { this.greeting = `Hello, ${name}!`; } }
import { Injectable, EventEmitter } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class SharedService { valueChanged = new EventEmitter(); private _value: number; get value(): number { return this._value; } set value(val: number) { this._value = val; this.valueChanged.emit(val); } }
import { Component } from '@angular/core'; import { SharedService } from './shared.service'; @Component({ selector: 'app-sibling1', template: ` `, }) export class Sibling1Component { value: number; constructor(private sharedService: SharedService) {} updateValue() { this.sharedService.value = this.value; } }
import { Component } from '@angular/core'; import { SharedService } from './shared.service'; @Component({ selector: 'app-sibling2', template: `In both examples, the EventEmitter class is part of the @angular/core library.Value: {{ value }}
`, }) export class Sibling2Component { value: number; constructor(private sharedService: SharedService) {} ngOnInit() { this.sharedService.valueChanged.subscribe(val => { this.value = val; }); } }