2017-04-14 1 views
2

実行時に動的にテンプレートを読み込み、レンダリングし、テンプレート内の動的データにバインドしようとしています。角型2で動的テンプレートをレンダリングするときに@Inputを提供する方法

Stackoverflowの質問How to render a dynamic template with components in Angular2と@ Linksonderの答えに続いて、私は読み込みとレンダリングの部分を実行しています。

@Inputデータを動的コンポーネントに追加し、{{ data }}などのテンプレートからデータをバインドできるようにデータを提供することができません。

それはテストinputProviderとインジェクターを追加するように、私はこの方法でngOnChanges()を拡張:

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 {... '' ''にクラスを保存しようとするのではなく、 '?' 通常はコンポーネントを基本的に定義するのと同じ方法です –

+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」デコレータが欠落していることが示唆されています。今はうまくいきます! –

関連する問題