2017-04-14 94 views
2

我試圖在運行時動態加載模板,將其渲染並綁定到模板內的動態數據。如何在Angular 2中呈現動態模板時提​​供@Input

繼stackoverflow的問題How to render a dynamic template with components in Angular2和@ Linksonder的答案我有加載和渲染部分的運行。

現在,我堅持將一個@Input數據添加到動態組件並提供數據,以便我可以從模板(如{{ data }})綁定到它。

我擴展以這種方式ngOnChanges(),使其增加了噴油器與測試inputProvider

createComponentFactory(this.compiler, compMetadata) 
    .then(factory => { 
    let inputProviders = [{provide: 'data', useValue: '1234'}]; 
    let resolvedInputs = ReflectiveInjector.resolve(inputProviders); 

    const injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.vcRef.parentInjector); 

    this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []); 
    }); 

但是,試圖訪問DynamicComponent注射器這種方式引發錯誤(我假設注射器不能解決):

... 
import { Injector} from '@angular/core'; 

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> { 

    const cmpClass = class DynamicComponent { 
    data: any; 

    constructor(private injector: Injector) { 
     this.data = this.injector.get('data'); 
    } 
    }; 

    const decoratedCmp = Component(metadata)(cmpClass); 

    @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] }) 
    class DynamicHtmlModule { } 

    return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) 
    .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => { 
    return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp); 
    }); 
} 

任何幫助表示讚賞。此外,如果您有其他解決問題的方法,請告訴我。

+0

我不知道是肯定的,但你可以試試:'@Component(元數據)類DynamicComponent {... }而不是試圖將類保存在'const's中? 同樣的方式,你通常會定義一個組件基本 –

+0

它有幫助嗎? –

+0

您可以直接設置組件 –

回答

0

我懷疑這應該爲你工作:

@Injectable() 
class DynamicComponent { 
    data: any; 

    constructor(private injector: Injector) { 
    this.data = this.injector.get('data'); 
    } 
} 

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> { 
    const decoratedCmp = Component(metadata)(DynamicComponent); 

    @NgModule({ imports: [CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] }) 
    class DynamicHtmlModule { } 

    compiler.clearCacheFor(decoratedCmp); 
    return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) 
     .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => { 
     return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp); 
     }); 
} 

Plunker Example

+0

的屬性如上所述,「@ Injectable」裝飾器丟失了。現在很好地工作! –

相關問題