server.component.ts
import {Component, OnInit, EventEmitter, Output} from '@angular/core'; @Component({ selector: 'app-server', templateUrl: './server.component.html', styleUrls: ['./server.component.css'] }) export class ServerComponent implements OnInit { // this is now an event @Output() statusChanged = new EventEmitter<{ serverId: number, time: Date }>(); status = 'offline'; constructor() { setTimeout(() => { this.status = 'online'; // fire event this.statusChanged.emit({serverId: 10, time: new Date()}); }, 5000); } ngOnInit() { } }
server.component.html
<p> server is {{status}} </p>
app.component.ts
import {Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { serverId; time; /** * receive data from event */ onServerStatusChanged(data: { serverId: number, time: Date }) { this.serverId = data.serverId; this.time = data.time; } }
app.component.html
<app-server (statusChanged)="onServerStatusChanged($event)"></app-server> <p>Server Id : {{serverId}}, Date : {{time}}</p>
Assigning an Alias to Custom Events
@Output('nicolas') nic = new EventEmitter<any>();
References
https://github.com/mhdr/AngularSamples/tree/master/013/my-app