2017-07-09 4 views
1

コンポーネントを引数として取り込み、bodyタグの最後にそのコンテンツをレンダリングするプラグインを作成しようとしています。 jQueryで動作するプラグインと似ています。Angular2 - 要求に応じてコンポーネントをレンダリングしてボディに追加する

@Component({ 
    selector: 'some-selector', 
    template: 'This is FirstComponent' 
}) 
class FirstComponent{} 

@Component({ 
    selector: 'app', 
    template: 'The root component' 
}) 
class AppComponent{ 
    // ImaginaryModalOpener is what i want to achieve. 
    // a standalone function that can take a component and render it in dom  
    // at the bottom of the body tag 
    ImaginaryModalOpener(FirstComponent); 
} 

ダイナミックコンポーネントのレンダリングに関する多くのstackoverflowに関する質問がありましたが、ルートコンポーネントでディレクティブやHTMLマークアップを使用して始めます。 私の場合、ルートテンプレートにはImaginaryModalOpener用のディレクティブまたはコンポーネントがありません。

私が何かを見逃してしまったことを指摘してください。

+0

[回答](https://stackoverflow.com/a/44853707/2545680)は解決策を提供するはずですが、コンテナrefを表示するのではなく、直接DOMノードを使用してコンポーネントを挿入します –

答えて

1

ViewContainerRef

how to get root viewContainerRef of angular2 aplicationAppComponentからを取得し、このViewContainerRefにコンポーネントを追加たとえばAngular 2 dynamic tabs with user-click chosen components

に示すように添加される成分は、AppComponentに兄弟として追加されます。 AppComponent<body>の子である場合、動的に追加されるコンポーネントも<body>の子になります。

+1

ありがとう!私は最終的にこのコードを思いつき、コンポーネントをボディに追加します。乾杯。 let factory = this.resolver.resolveComponentFactory(options.component); let newNode = document.createElement( 'div'); document.body.appendChild(newNode); const ref:any = factory.create(this.injector、[]、newNode); this.app.attachView(ref.hostView); –

関連する問題