Bhushan Gadekar
Bhushan Gadekar

Reputation: 13805

use dynamic component loader in angular2?

I have created following application using dynamicComponentloader of angular2 using typeScript. But my child component is not getting rendered. Snapshot of my app

my component:

import {Component, Directive, ElementRef, Renderer,DynamicComponentLoader} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {DynamicBody1Component} from './ICICI-DYNAMIC-BODY-1.component';

@Directive({
  selector: '[x-large]'
})
export class XLarge {
  constructor(element: ElementRef, renderer: Renderer) {
    // we must interact with the dom through Renderer for webworker/server to see the changes
    renderer.setElementStyle(element.nativeElement, 'fontSize', 'x-large');
  }
}


@Component({
  selector: 'app',
  directives: [
    ...ROUTER_DIRECTIVES,
    XLarge
  ],
  styles: [`
    .router-link-active {
      background-color: lightgray;
     }`
    ],
  template: `
    <div>    
        <div>
            <span x-large>Hello, {{ name }}!</span>
        </div>
        <div>
            <div #container></div>
        </div>
      </div>
      `
 })
export class App {
  name: string = 'Angular 2';
  public dynamicComponentLoader: DynamicComponentLoader;  
  constructor(dynamicComponentLoader: DynamicComponentLoader, private     elementRef: ElementRef) {}

  ngOnInit() {
    this.dynamicComponentLoader.loadIntoLocation(DynamicBody1Component, this.elementRef, 'container');

  }
}

is anything wrong here? Thanks in advance.

Upvotes: 2

Views: 3013

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658263

For an up-to-date example see Angular 2 dynamic tabs with user-click chosen components

original

You can't use dynamicComponentLoader in constructor() anymore. Move it to ngOnInit()

import {Component, Directive, ElementRef, Renderer,DynamicComponentLoader} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {DynamicBody1Component} from './DYNAMIC-BODY-1.component';

@Directive({
  selector: '[x-large]'
  host: {
    '[style.fontSize]': 'x-large',
  }
})
export class XLarge {
}


@Component({
  selector: 'app',
  directives: [
    ...ROUTER_DIRECTIVES,
    XLarge
  ],
  styles: [`
    .router-link-active {
      background-color: lightgray;
    }
  `],
  template: `
  <div>    
    <div>
      <span x-large>Hello, {{ name }}!</span>
    </div>
    <div>
        <div #container></div>
    </div>
  </div>
  `
})
export class App {
  name: string = 'Angular 2';
  constructor(private dynamicComponentLoader: DynamicComponentLoader, private elementRef: ElementRef) {}

  ngOnInit() {
    this.dynamicComponentLoader.loadIntoLocation(DynamicBody1Component, this.elementRef, 'container');

  }
}

Upvotes: 2

Related Questions