Last active
August 29, 2021 04:33
-
-
Save tjoskar/67687b6a6efd16fe8567dac138ef9128 to your computer and use it in GitHub Desktop.
How to use observables in angular 2 template
This file contains 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 { Directive, Input, TemplateRef, ViewContainerRef, EmbeddedViewRef, ChangeDetectorRef } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import { Subscription } from 'rxjs/Subscription'; | |
@Directive({ | |
selector: '[streamContext][streamContextOn]' | |
}) | |
export class StreamContext { | |
@Input() streamContextOn: Observable<any>; | |
templateRef: TemplateRef<any>; | |
vcr: ViewContainerRef; | |
cd: ChangeDetectorRef; | |
_viewRef: EmbeddedViewRef<any>; | |
subscription: Subscription; | |
constructor(templateRef: TemplateRef<any>, vcr: ViewContainerRef, cd: ChangeDetectorRef) { | |
this.templateRef = templateRef; | |
this.vcr = vcr; | |
this.cd = cd; | |
} | |
ngOnInit() { | |
this.subscription = this.streamContextOn.subscribe(state => { | |
if (!this._viewRef) { | |
this._viewRef = this.vcr.createEmbeddedView(this.templateRef, { '$implicit': state }); | |
} else { | |
this._viewRef.context.$implicit = state; | |
} | |
this.cd.markForCheck(); | |
}); | |
} | |
ngOnDestroy() { | |
this.subscription.unsubscribe(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
useage: