Last active
November 21, 2021 00:31
-
-
Save crshmk/37b12a78ee2c245b7f081d0ad6a31f18 to your computer and use it in GitHub Desktop.
ngModel updating shared service state with BehaviorSubject
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 { BehaviorSubject } from 'rxjs/BehaviorSubject'; | |
export class ObsService { | |
private val$:BehaviorSubject<number> = new BehaviorSubject(42); | |
val = this.val$.asObservable(); | |
} |
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 { ObsService } from './obs.service'; | |
@Component({ | |
selector: 'app-one', | |
template: ` | |
<h4>Component One</h4> | |
<p>{{value}}</p> | |
`, | |
styles: [] | |
}) | |
export class OneComponent implements OnInit { | |
constructor(private obsService: ObsService) {} | |
value: number; | |
ngOnInit() { | |
this.obsService.val | |
.subscribe(v => this.value = v, () => 'err'); | |
} | |
} |
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 { ObsService } from './obs.service'; | |
@Component({ | |
selector: 'app-two', | |
template: ` | |
<h4>Component Two</h4> | |
<p>{{value}}</p> | |
<input [ngModel]="obsService.val$ | async" (ngModelChange)="obsService.val$.next($event)" /> | |
`, | |
styles: [] | |
}) | |
export class TwoComponent implements OnInit { | |
constructor(private obsService: ObsService) {} | |
value: number; | |
ngOnInit() { | |
this.obsService.val | |
.subscribe(v => this.value = v); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment