Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created May 11, 2018 20:41
Show Gist options
  • Save amcdnl/76fd2e68edf8fee6fbb764520f95f302 to your computer and use it in GitHub Desktop.
Save amcdnl/76fd2e68edf8fee6fbb764520f95f302 to your computer and use it in GitHub Desktop.
import {
Component,
ChangeDetectionStrategy,
Input,
AfterViewInit,
TemplateRef,
ViewChild,
OnInit,
EmbeddedViewRef,
OnChanges,
OnDestroy,
ViewContainerRef,
ElementRef
} from '@angular/core';
import { GridCellComponent } from './grid-cell.component';
import { FlexResizeDirective } from 'shared/components/flex';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { CdkPortalOutlet, TemplatePortal } from '@angular/cdk/portal';
import { FlexDirective } from '@angular/flex-layout';
@Component({
selector: 'df-grid-internal-cell',
template: `
<div class="df-grid-cell-container">
<span
*ngIf="!cellTemplate.template"
[innerHTML]="row[cellTemplate.field]">
</span>
<span
*ngIf="cellTemplate.template"
cdkPortalOutlet>
</span>
</div>
`,
host: {
'[class.df-grid-cell]': 'true'
},
styleUrls: ['./grid-internal-cell.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class GridCellInternalComponent extends FlexResizeDirective implements OnInit, OnChanges, AfterViewInit, OnDestroy {
/**
* Row we are rendering.
*/
@Input() row: any;
/**
* Cell data we are rendering.
*/
@Input() cellTemplate: GridCellComponent;
@ViewChild(CdkPortalOutlet) outlet: CdkPortalOutlet;
private _outletRef: EmbeddedViewRef<any>;
private _templatePortal: TemplatePortal;
private _destroy$ = new Subject();
constructor(
private _vcr: ViewContainerRef,
elementRef: ElementRef,
flexDirective: FlexDirective
) {
super(elementRef, flexDirective);
}
ngOnInit() {
this.cellTemplate.flexChange
.pipe(takeUntil(this._destroy$))
.subscribe((res: any) => this.updateStyle(res));
if (this.cellTemplate.template) {
this._templatePortal = new TemplatePortal(
this.cellTemplate.template.templateRef,
this._vcr,
{
row: this.row,
value: this.row[this.cellTemplate.field]
}
);
}
}
ngAfterViewInit() {
if (this._templatePortal) {
this._outletRef = this.outlet.attach(this._templatePortal);
}
}
ngOnChanges() {
this.update();
}
ngOnDestroy() {
this._destroy$.next();
this._destroy$.complete();
}
/**
* Update the context.
*/
update() {
if (this._templatePortal) {
this._templatePortal.context.row = this.row;
this._templatePortal.context.value = this.row[this.cellTemplate.field];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment