Skip to content

Instantly share code, notes, and snippets.

@nirkaufman
Created March 19, 2020 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nirkaufman/3fe438d1a85bc557ddd6698a7957f8ed to your computer and use it in GitHub Desktop.
Save nirkaufman/3fe438d1a85bc557ddd6698a7957f8ed to your computer and use it in GitHub Desktop.
import {
AfterViewInit,
Component,
ComponentFactoryResolver,
ComponentRef,
Injector,
ViewChild,
ViewContainerRef,
ViewRef
} from '@angular/core';
import {TableComponent} from "./table.component";
@Component({
selector: 'app-root',
template: `
<div class="container m-5">
<h1>
<span class="text-muted">MasterClass</span>Playground
</h1>
<button (click)="toggleView()">toggle View</button>
<ng-container #container></ng-container>
</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;
private tableComponent: ComponentRef<TableComponent>;
private tableView: ViewRef;
constructor(private cfr: ComponentFactoryResolver,
private injector: Injector) {
}
ngAfterViewInit(): void {
const tableFactory = this.cfr.resolveComponentFactory(TableComponent);
this.tableComponent = tableFactory.create(this.injector);
this.tableView = this.container.insert(this.tableComponent.hostView);
}
toggleView() {
const index = this.container.indexOf(this.tableView);
if (index >= 0) {
this.tableView = this.container.detach(index);
} else {
this.tableView = this.container.insert(this.tableView)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment