Created
November 11, 2017 13:25
-
-
Save pglazkov/d9406d820846f9980a6f654d3c0da305 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 { 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