Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2.0 final: How to instantiate a component from code

Tags:

angular

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:

  • I will need to be able to use the inputs/outputs of the child component
  • I'm explictly not talking about compiling a new component on the fly like these two issues describe: How can I use/create dynamic template to compile dynamic Component with Angular 2.0? and Equivalent of $compile in Angular 2

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.

  • How to instantiate and render Angular2 components?
  • Is it possible to manually instantiate component in angular 2
like image 463
Robba Avatar asked Sep 25 '16 09:09

Robba


2 Answers

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 {}
like image 182
slaesh Avatar answered Oct 08 '22 11:10

slaesh


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;
    }
like image 21
Puneeth Rai Avatar answered Oct 08 '22 10:10

Puneeth Rai