Last active
April 2, 2018 11:01
-
-
Save cgatian/7bf5276013e2dfcfbd61e87ab15e7566 to your computer and use it in GitHub Desktop.
Dynamically creating a component in DOM location
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
@Component({ | |
selector: 'app-root', | |
template: `` | |
}) | |
export class AppComponent implements OnInit { | |
private componentRef; | |
constructor( | |
private componentFactoryResolver: ComponentFactoryResolver, | |
private injector: Injector | |
) { } | |
ngOnInit() { | |
// Locate an element that exists on the page | |
const headerElement = document.querySelector('#pageHeader'); | |
// Locate the component factory for the HeaderComponent | |
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HeaderComponent); | |
// Generate an instance of the HeaderComponent | |
this.componentRef = componentFactory.create(this.injector, [], headerElement); | |
// Attach to the component to Angular's component tree for dirty checking | |
this.applicationRef.attachView(this.componentRef.hostView); | |
} | |
} |
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector,
private applicationRef: ApplicationRef,
) { }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You forgot to import
ApplicationRef