2016-03-03 90 views
2

我已经使用typeScript创建了以下使用angular2的dynamicComponentloader的应用程序。 但我的孩子组件没有得到渲染。 Snapshot of my app在angular2中使用动态组件加载器?

我的组件:

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

    } 
} 

是这里有什么问题? 在此先感谢。

回答

2

对于跟上时代的例子中看到Angular 2 dynamic tabs with user-click chosen components

不能使用在constructor()dynamicComponentLoader了。它移动到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'); 

    } 
} 
+0

我想你的解决方案,现在我得到这个错误;'例外:类型错误:无法读取属性“loadIntoLocation类型错误:在[空] 原始异常无法读取属性未定义“loadIntoLocation” 'undefined' ...查看有问题的代码 –

+0

对不起,忘了在构造函数之前删除'App'中的一行。 –

+0

@ gunter.its仍然无法正常工作。详情请参阅快照。我正在使用通用启动器进行服务器端渲染。没有错误显示。但我的组件也没有得到加载浏览器。 –