2017-09-16 19 views
0

ここでは、これを行う方法とネットの周りのいくつかの例を見てきましたが、試してみると、子コンポーネントがDOMのピアとして挿入されますターゲットコンポーネントここ は、私が働いているマークアップである:ここでは角度コンポーネントを他のコンポーネントの子として動的に挿入する

<div #target></div> 
<button (click)="AddTile()">Add Tile</button> 

は、親コンポーネントのコードです:

import { Component, ComponentFactoryResolver, ViewContainerRef, ViewChild }  from '@angular/core'; 
import { TileComponent } from './tile/tile.component'; 

@Component({ 
selector: 'app-root', 
templateUrl: './app.component.html', 
styleUrls: ['./app.component.css'] 
}) 

export class AppComponent{ 
    title = 'app works!'; 

    @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef; 

    constructor(private componentFactoryResolver: ComponentFactoryResolver, private viewContainerRef: ViewContainerRef) {} 

    AddTile() { 
    const factory = this.componentFactoryResolver.resolveComponentFactory(TileComponent); 
    const res = this.target.createComponent(factory); 
    } 
} 

このコードの出力は次のとおりです。

<div #target></div> 
<tile-component></tile-component> 
<tile-component></tile-component> 

予想される出力は次のようになります。

<div #target> 
    <tile-component></tile-component> 
    <tile-component></tile-component> 
</div> 
+0

ユーザアクションに基づいて異なる動的コンポーネントを使用する予定がありますか? – Aravind

+0

いいえ、同じコンポーネントです。ユーザーの操作にも基づいていませんが、実行時にさまざまな数のコンポーネントを動的に追加する必要があります。ここではPOCの一部としてボタンを使用しています。 – Lazloman

答えて

2

ng-containerをターゲットとして使用し、DOMに要素を残さないようにすることができます。 div

<div> 
    <ng-container #target></ng-container> 
</div> 
+0

これは動作します。私はdivを使用しようとしましたが、divをDOMに残していることを除いて同じ結果が得られますが、これはショーストッパーではありませんが、依然として望ましくありません。ありがとうございました – Lazloman

+0

私は今、構成要素が常に同じであるので、今思っています。必要なコンポーネントの数が長さのダミー配列をループするテンプレートに 'ngFor'を追加できませんか? –

+0

これもオプションです。私はこれを行うさまざまな方法を調査しています。ループは実際には最も簡単です。 – Lazloman

関連する問題