Skip to content

Instantly share code, notes, and snippets.

@ghetolay
Last active August 8, 2017 11:10
Show Gist options
  • Save ghetolay/d1b9a16f472ad857611b9f43ebcb714f to your computer and use it in GitHub Desktop.
Save ghetolay/d1b9a16f472ad857611b9f43ebcb714f to your computer and use it in GitHub Desktop.
Custom template outlet to avoid view recreation on context changes
interface Context {
$implicit: any
}
@Directive({
selector: '[imbaTemplateOutlet]'
})
export class ImbaTemplateOutlet {
@Input()
imbaTemplateOutlet: TemplateRef<Context>;
@Input()
private contextItem: any;
viewRef: EmbeddedViewRef<Context> | null = null;
constructor(private viewContainer: ViewContainerRef) {}
ngOnChanges(changes: SimpleChanges) {
if ('imbaTemplateOutlet' in changes) {
if (this.viewRef === null)
this.viewContainer.remove(this.viewContainer.indexOf(this.viewRef));
this.viewRef = this.imbaTemplateOutlet ?
this.viewContainer.createEmbeddedView(this.imbaTemplateOutlet, {$implicit: this.contextItem}) :
null;
}
else if ('contextItem' in changes && this.viewRef)
this.viewRef.context.$implicit = this.contextItem;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment