Skip to content

Instantly share code, notes, and snippets.

@crshmk
Last active November 21, 2021 00:31
Show Gist options
  • Save crshmk/37b12a78ee2c245b7f081d0ad6a31f18 to your computer and use it in GitHub Desktop.
Save crshmk/37b12a78ee2c245b7f081d0ad6a31f18 to your computer and use it in GitHub Desktop.
ngModel updating shared service state with BehaviorSubject
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
export class ObsService {
private val$:BehaviorSubject<number> = new BehaviorSubject(42);
val = this.val$.asObservable();
}
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');
}
}
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