event-bus.service.ts
import {EventEmitter, Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EventBusService {
statusUpdate = new EventEmitter<string>();
constructor() {
}
}
input.component.html
<label>
Name
<input type="text" (change)="onInputChanged($event)">
</label>
input.component.ts
import {Component, Input, OnInit} from '@angular/core';
import {EventBusService} from '../services/event-bus.service';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
inputText: string;
constructor(private eventBus: EventBusService) {
}
ngOnInit() {
}
onInputChanged(event: Event) {
this.inputText = (event.target as HTMLInputElement).value;
this.eventBus.statusUpdate.emit(this.inputText);
}
}
output.component.html
<p>
{{output}}
</p>
output.component.ts
import {Component, OnInit} from '@angular/core';
import {EventBusService} from '../services/event-bus.service';
@Component({
selector: 'app-output',
templateUrl: './output.component.html',
styleUrls: ['./output.component.css']
})
export class OutputComponent implements OnInit {
output: string;
constructor(private eventBus: EventBusService) {
}
ngOnInit() {
this.eventBus.statusUpdate.subscribe((status: any) => {
this.output = status;
});
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { InputComponent } from './input/input.component';
import { OutputComponent } from './output/output.component';
import {EventBusService} from './services/event-bus.service';
@NgModule({
declarations: [
AppComponent,
InputComponent,
OutputComponent
],
imports: [
BrowserModule
],
providers: [EventBusService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<app-input></app-input>
<app-output></app-output>
References
https://github.com/mhdr/AngularSamples/tree/master/020/my-app