Skip to content

Instantly share code, notes, and snippets.

@pglazkov
Created November 11, 2017 13:25
Show Gist options
  • Save pglazkov/d9406d820846f9980a6f654d3c0da305 to your computer and use it in GitHub Desktop.
Save pglazkov/d9406d820846f9980a6f654d3c0da305 to your computer and use it in GitHub Desktop.
import { Component } from '@angular/core';
import { ComponentFactoryService } from './component-factory.service';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-home',
template: '<div #host></div>'
})
export class HomeComponent {
@ViewChild('host', {read: ViewContainerRef})
hostEl: ViewContainerRef;
constructor(private componentFactoryService: ComponentFactoryService) {
}
// Option 1. Add the component as a child of "body"
createComponentAndAddItToBody() {
let componentRef = this.componentFactoryService.createComponent(DynamicComponent);
// Access the instance of the component class via "componentRef.instance":
// componentRef.instance.functionOnComponentClass();
}
// Option 2. Add the component as a child of the "div" element in the template
// of this "HomeComponent".
createComponentAndAddItAsChildOfHostDiv() {
let componentRef = this.componentFactoryService.createComponent(DynamicComponent, this.hostEl);
// Access the instance of the component class via "componentRef.instance":
// componentRef.instance.functionOnComponentClass();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment