Skip to content

Instantly share code, notes, and snippets.

@stupidly-logical
Created September 6, 2019 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stupidly-logical/a34e272156b498513505127967aec851 to your computer and use it in GitHub Desktop.
Save stupidly-logical/a34e272156b498513505127967aec851 to your computer and use it in GitHub Desktop.
Service based communication between Child and Parent in Angular
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<button
(click)="onAddTimestamp()"
>
Add Timestamp
</button>
<app-child
[allData] = "dataArr"
></app-child>
import { Component } from '@angular/core';
import { DataService } from './data-service.service'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
dataArr = [];
constructor(private dataService: DataService){}
onAddTimestamp() {
let timestamp = new Date();
this.dataArr.push(timestamp);
this.dataService.setLatestData(timestamp);
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { DataService } from './data-service.service';
import { ChildComponent } from './child/child.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent, ChildComponent ],
bootstrap: [ AppComponent ],
providers: [DataService]
})
export class AppModule { }
<p>
Latest Data: {{ latestData }}
</p>
<h3>List:</h3>
<li *ngFor="let data of allData">
{{ data }}
</li>
import { Component, OnInit, Input } from '@angular/core';
import { DataService } from '../data-service.service';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() allData: [];
latestData: any;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.dataUpdated.subscribe((data) => {
this.latestData = data;
});
}
}
import { Injectable, EventEmitter } from '@angular/core';
@Injectable({
providedIn: "root"
})
export class DataService {
dataUpdated:EventEmitter<any> = new EventEmitter();
constructor() { }
setLatestData(data) {
this.dataUpdated.emit(data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment