Skip to content

Instantly share code, notes, and snippets.

@tjoskar
Last active August 29, 2021 04:33
Show Gist options
  • Save tjoskar/67687b6a6efd16fe8567dac138ef9128 to your computer and use it in GitHub Desktop.
Save tjoskar/67687b6a6efd16fe8567dac138ef9128 to your computer and use it in GitHub Desktop.
How to use observables in angular 2 template
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();
}
}
@tjoskar
Copy link
Author

tjoskar commented Dec 26, 2016

useage:

<div *streamContext="let person on person$">
  <p>{{ person.id }}</p>
  <p>{{ person.title }}</p>
  <p>{{ person.body }}</p>
</div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment