Skip to content

DynamicComponentClass

Ścibor Rudnicki edited this page Jul 7, 2017 · 2 revisions

DynamicComponentClass

Extend for component class to dynamically create new component

Usage

Step 1. Create component you want to dynamically create

// dynamic.component.ts

import { Component, ComponentFactoryResolver, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'dynamic-component',
  template: 'Dynamic component created succesfully'
})
export class DynamicComponent {
  key = 'defined';
  public model = {
    defined: true
  };

  @Output() event: EventEmitter<any> = new EventEmitter();

  emit() {
    this.event.emit('event');
  }
}

Step 2. Create component that will use DynamicComponentClass and create new DynamicComponent

// default.component.ts

import { Component, ComponentFactoryResolver } from '@angular/core';

import { DynamicComponentClass } from '@ngx-core/common';
import { DynamicComponent } from './dynamic.component'

@Component({
  selector: 'default-component',
  template: '<div #container></div>' // create #container variable
})
export class DefaultComponent extends DynamicComponentClass {
  public model = {};
  public key = 'notdefined';

  constructor(componentFactoryResolver: ComponentFactoryResolver) {
    super(componentFactoryResolver);

    this.create(DynamicComponent);
    this.key = 'defined';
    this.model = {
      defined: true
    };

    this.set('key'); // set component instance key variable value from this class to 'defined'
    this.set(['model','key']); // set component instance key variables value from this class

    // subscribe to EventEmitter - event Output
    this.subscribe('event', (result) => {
      console.log(result);
    });
  }
  // get private variable class _component with is newely created component
  public component() {
    return this.__get('__component');
  }

  // create component
  public create(component: any): void {
    this.__create(component); // protected method from DynamicComponentClass
  }
  public destroy(): void {
    this.__destroy(); // protected method from DynamicComponentClass
  }
  public set(key: string | Array<string>) {
    this.__set(key); // protected method from DynamicComponentClass
  }
  public subscribe(key: string, callback?: Function): void {
    this.__subscribe(key, callback); // protected method from DynamicComponentClass
  }
}

Step 3. Create module

// primary.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { DynamicComponent } from './dynamic.component';
import { DefaultComponent } from './default.component';

@NgModule({
  imports: [CommonModule],
  declarations: [DynamicComponent, DefaultComponent],
  entryComponents: [DynamicComponent] // <--- set DynamicComponent in entryComponents
})
export class PrimaryModule { }
Clone this wiki locally