2017-11-17 4 views
1

私は3つの要素を持っている、と私は値に基づいて、別のコンポーネントのHTMLにGetリクエストから受け取ったそれらのいずれかを注入したい:角度動的に特定の成分を注入

器Comp1、器Comp2、器Comp3

現在方法は、特に3つの構成要素は、すぐにでは20

<Comp1 *ngIf="data.value === 'comp_1'"></Comp1> 
    <Comp2 *ngIf="data.value === 'comp_2'"></Comp2> 
    <Comp3 *ngIf="data.value === 'comp_3'"></Comp3> 

になるかもしれとき、私は簡単に関数呼び出しを経由してJSXの作品を注入することができる理想的な未満リアクトされていますが、私は角度でこれを行うためのベストプラクティスについてはよく分かりません

+0

ルック - > https://angular.io/guide/dynamic-component-loader –

+2

あなたは 'ngSwitch'またはhttps://stackoverflow.com/questions/36325212/angular-2-dynamic-のようなものを使用することができますtabs-with-user-click-selected-components/36325468#36325468をクリックします。 https://angular.io/api/common/NgComponentOutlet –

+0

NgComponentOutletも参照して、おかげでそれを行うための非常に滑らかな印象の方法です。 –

答えて

0

ここにはNgComponentOutletの使用例があります。あなたは二つの成分があるとしましょう:

@Component({ 
    selector: 'dynamic-component-one', 
    template: `<p>I'm the Component 1</p>` 
}) 
export class FirstDynamicComponent {} 

@Component({ 
    selector: 'dynamic-component-two', 
    template: `<p>I'm the Component 2</p>` 
}) 
export class SecondDynamicComponent {} 

以下のコンポーネントはデフォルトでFirstDynamicComponentをロードしていますが、ボタンをクリックした場合SecondDynamicComponentに置き換え:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <button (click)="switchComponents()">Swith Components:</button> 
    <ng-container *ngComponentOutlet="content"></ng-container> 
    ` 
}) 
export class AppComponent { 
    comp1 = FirstDynamicComponent; 
    comp2 = SecondDynamicComponent; 

    content = this.comp1; 

    switchComponents() { 
    this.content = this.comp2; 
    } 
} 

は、動的コンポーネントの両方を登録することを忘れないでください。

@NgModule({ 
    imports: [...], 
    declarations: [ 
     AppComponent, 
     FirstDynamicComponent, 
     SecondDynamicComponent 
    ], 
    entryComponents: [ 
     FirstDynamicComponent, 
     SecondDynamicComponent 
    ] 
}) 
export class AppModule { } 

StackBlitz example

:そのモジュールの entryComponentsセクションでこの時
関連する問題