2015-10-09 44 views
4

我是而不是使用打字稿,但使用ES6和angular2 alpha39來動態加載組件。以下代碼與我在應用程序中的代碼類似。我注意到的是angular2不創建的一個實例DynamicComponentLoader也不ElementRef並注入到構造函數中。他們沒有定義。如何在ES6中使用angular2 DynamicComponentLoader?

如何使用ES6和angular2 alpha39注入DynamicComponentLoader?

import {Component, View, Inject, DynamicComponentLoader, ElementRef } from 'angular2/angular2' 

@Component({ 
    selector: 'dc', 
    bindings: [ DynamicComponentLoader ] 
}) 
@View({ 
    template: '<b>Some template</b>' 
}) 

class DynamicComponent {} 

@Component({ 
    selector: 'my-app' 
}) 
@View({ 
    template: '<div #container></div>' 
}) 
@Inject(DynamicComponentLoader) 
@Inject(ElementRef) 
export class App { 
    constructor(
    dynamicComponentLoader, 
    elementRef 
) { 
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container'); 
    } 
} 

回答

12

如果你想在ES7寫代碼,我覺得在這個時候指定注射用最簡潔的方法是使用靜態getter方法parameters

import {Component, View, DynamicComponentLoader, ElementRef } from 'angular2/angular2' 

@Component({ 
    selector: 'my-app' 
}) 
@View({ 
    template: '<div #container></b>' 
}) 
export class App { 

    static get parameters() { 
    return [[DynamicComponentLoader], [ElementRef]]; 
    } 

    constructor(dynamicComponentLoader, elementRef) { 
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container'); 
    } 
} 

this plunker

如果你想在ES6中編寫代碼,它不支持裝飾器,你還必須使用靜態獲取器來獲得annotations屬性。在這種情況下,你必須導入ComponentMetadataViewMetadata代替ComponentView例如:

import {ComponentMetadata, ViewMetadata, DynamicComponentLoader, ElementRef } from 'angular2/angular2'; 

export class App { 

    static get annotations() { 
    return [ 
     new ComponentMetadata({ 
     selector: 'app' 
     }), 
     new ViewMetadata({ 
     template: '<div #container></b>' 
     }) 
    ]; 
    } 

    static get parameters() { 
    return [[DynamicComponentLoader],[ElementRef]]; 
    } 

    constructor(dynamicComponentLoader, elementRef) { 
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container'); 
    } 
} 

this plunker

+0

救星,但現在裝修正在爲@Component – Blacksonic