Skip to content

Instantly share code, notes, and snippets.

@cgatian
Last active April 2, 2018 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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);
}
}
@abdel-ships-it
Copy link

You forgot to import ApplicationRef

@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