在angular2中使用动态组件加载器?

时间:2016-03-03 11:01:27

标签: angular typescript dynamic-loading

我使用typeScript使用angular2的dynamicComponentloader创建了以下应用程序。 但是我的子组件没有被渲染。 Snapshot of my app

我的组件:

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');

  }
}

这里有什么不对吗? 提前谢谢。

1 个答案:

答案 0 :(得分:2)

有关最新示例,请参阅Angular 2 dynamic tabs with user-click chosen components

<强>原始

您不能再在dynamicComponentLoader中使用constructor()了。将其移至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');

  }
}