Created
March 19, 2020 20:45
-
-
Save nirkaufman/3fe438d1a85bc557ddd6698a7957f8ed to your computer and use it in GitHub Desktop.
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 { | |
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