Skip to content

Instantly share code, notes, and snippets.

@cgatian
Last active October 25, 2017 01:24
Show Gist options
  • Save cgatian/a73e8cb60e9aa300b18f8a197b8f58ee to your computer and use it in GitHub Desktop.
Save cgatian/a73e8cb60e9aa300b18f8a197b8f58ee to your computer and use it in GitHub Desktop.
@Component({
selector: 'my-app',
template: `
<ng-template #testTemplate let-name>
<div>User {{ name }} </div>
</ng-template>`
})
export class AppComponent implements OnInit {
private componentRef;
@ViewChild('testTemplate') testTemplate: TemplateRef<any>;
constructor(
private injector: Injector,
private viewContainerRef: ViewContainerRef,
) { }
ngOnInit() {
// Locate an element that exists on the page
const headerElement = document.querySelector('#pageHeader');
// Locate the component factory for the HeaderComponent
const embeddedView = this.viewContainerRef.createEmbeddedView(
this.testTemplate,
{ $implicit: 'Bob'},
);
// Place element in correct location in DOM
embeddedView.rootNodes.forEach(rootNode => headerElement.appendChild(rootNode));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment