I'm looking for a way to instantiate a component in Angular2 from within the code of another component. Unlike the many people that have asked a similar question I'm not so much interested in dynamically compiling a new component, just instantiating and inserting one that already exists in my application.
For instance:
Say I have two components:
dashboard-item.component.ts
import { Component } from "@angular/core";
@Component({
selector: "dashboard-item",
template: "Some dashboard item with functionality"
})
export class DashboardItemComponent {
constructor() {}
onInit() {}
}
dashboard.component.ts
import { Component } from "@angular/core";
@Component({
selector: "dashboard",
template: "<h1>Dashboard!</h1><div #placeholder></div>"
})
export class DashboardComponent {
constructor() {}
onInit() {}
}
What I'm looking for is a way to create a DashboardItemComponent in the onInit of the DashboardComponent and add it to the #placeholder div.
Two things to note:
These two earlier issues ask a similar question, but their answers are either rather lackluster or pertain to earlier (beta) versions of Angular2 and no longer seem to work.
Here's a working demo: https://plnkr.co/edit/pgkgYEwSwft3bLEW95Ta?p=preview
import {Component, NgModule, ViewChild, ElementRef, Input, Output, EventEmitter, ViewContainerRef, ComponentRef, ComponentFactoryResolver, ReflectiveInjector} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'any-comp',
template: '<div (click)="clicked.emit($event)">here i am.. {{name}}</div>'
})
export class AnyComponent {
@Input() name;
@Output() clicked = new EventEmitter();
constructor() {
console.log('some1 created me.. ! :)');
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<template #placeHolder>
</template>
</div>
`,
})
export class App {
@ViewChild('placeHolder', {read: ViewContainerRef}) private _placeHolder: ElementRef;
name:string;
constructor(private _cmpFctryRslvr: ComponentFactoryResolver) {
this.name = 'Angular2'
}
ngOnInit() {
let cmp = this.createComponent(this._placeHolder, AnyComponent);
// set inputs..
cmp.instance.name = 'peter';
// set outputs..
cmp.instance.clicked.subscribe(event => console.log(`clicked: ${event}`));
// all inputs/outputs set? add it to the DOM ..
this._placeHolder.insert(cmp.hostView);
}
public createComponent (vCref: ViewContainerRef, type: any): ComponentRef {
let factory = this._cmpFctryRslvr.resolveComponentFactory(type);
// vCref is needed cause of that injector..
let injector = ReflectiveInjector.fromResolvedProviders([], vCref.parentInjector);
// create component without adding it directly to the DOM
let comp = factory.create(injector);
return comp;
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, AnyComponent ], // ! IMPORTANT
entryComponents: [ AnyComponent ], // ! IMPORTANT --> would be lost due to Treeshaking..
bootstrap: [ App ]
})
export class AppModule {}
In case if anyone wants to avoid any statement in accepted answer here is the snippet
public createComponent<T>(vCref: ViewContainerRef, type: Type<T>): ComponentRef<T> {
let factory = this._cmpFctryRslvr.resolveComponentFactory(type);
// vCref is needed cause of that injector..
let injector = ReflectiveInjector.fromResolvedProviders([], vCref.parentInjector);
// create component without adding it directly to the DOM
let comp = factory.create(injector);
return comp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With