Created
September 9, 2019 18:17
-
-
Save AvocadoVenom/fcb0f9e8e8a5a4c85da5c3d69ab2505b to your computer and use it in GitHub Desktop.
An angular child-to-parent communication using service.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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