Skip to content

Instantly share code, notes, and snippets.

@AvocadoVenom
Created September 9, 2019 18:17
Show Gist options
  • Select an option

  • Save AvocadoVenom/fcb0f9e8e8a5a4c85da5c3d69ab2505b to your computer and use it in GitHub Desktop.

Select an option

Save AvocadoVenom/fcb0f9e8e8a5a4c85da5c3d69ab2505b to your computer and use it in GitHub Desktop.
An angular child-to-parent communication using service.
import { Component, OnInit } from '@angular/core';
import { DataService } from "./data.service";
@Component({
selector: 'app-sibling',
template: `
{{message}}
<button (click)="newMessage()">New Message</button>
`
})
export class SiblingComponent implements OnInit {
message:string;
constructor(private service: DataService) { }
ngOnInit() {
this.data.msg.subscribe(m => this.message = m);
}
newMessage() {
this.service.setMessage("Hello from child");
}
}
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private msg = new BehaviorSubject('Init');
constructor() { }
setMessage(newContent: string) {
this.msg.next(newContent);
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from "./data.service";
@Component({
selector: 'app-parent',
template: `
{{message}}
`
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.msg.subscribe(m => this.message = m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment