Skip to content

Instantly share code, notes, and snippets.

@cgatian
Last active April 2, 2018 11:01
Show Gist options
  • Save cgatian/7bf5276013e2dfcfbd61e87ab15e7566 to your computer and use it in GitHub Desktop.
Save cgatian/7bf5276013e2dfcfbd61e87ab15e7566 to your computer and use it in GitHub Desktop.
Dynamically creating a component in DOM location
@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);
}
}
@code-vagabond
Copy link

code-vagabond commented Apr 2, 2018

 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