2017-12-18 88 views
0

讓我們創建一個基於字符串動態組件說我有這給了我這樣的一個API:在角5

{ 
    title: 'title1', 
    type: 'FullComponent' 
}, 
{ 
    title: 'title2', 
    type: 'HalfComponent' 
}, 
{ 
    title: 'title3', 
    type: 'HalfComponent' 
}, 
{ 
    title: 'title4', 
    type: 'ThirdComponent' 
}, 
{ 
    title: 'title5', 
    type: 'ThirdComponent' 
}, 
{ 
    title: 'title6', 
    type: 'ThirdComponent' 
}, 

我想基於這些type值動態生成組件。

// app.component.ts 

ngOnInit() { 
    this.getWidget() 
     .subscribe(
     data => { 
     }, 
     error => { 
      ??? 
     } 
    ); 
} 

getWidget() { 
    return this.http.get('www.api.com'); 
} 

data返回上面的json。 我該怎麼做才能生成這些組件(這些組件已經使用Angular CLI創建,因此它們已經存在)? 謝謝:)

+1

,但所有這些組件預計將在模塊 – Aravind

+0

幫助的'entryComponents'我明白這一點,你從API獲取組件列表,然後使用這些組件準備應用程序並使用該應用程序?我說得對嗎? –

+0

我已經在我的應用程序體系結構中創建了所有三個組件。我只是想根據API中的字符串值生成這些字符串。所以我想創建一個組件生成器,它可以這樣做:'< THRID組分>' – GreatHawkeye

回答

0

我想創建一個組件管理器,它將使FullComponent,HalfComponent或ThirdComponent在輸入的功能:

manager.component.html

<ng-container *ngIf="component === 'FullComponent'"> 
    <app-full-component></app-full-component> 
</ng-container> 

<ng-container *ngIf="component === 'HalfComponent'"> 
    <app-half-component></app-half-component> 
</ng-container> 

<ng-container *ngIf="component === 'ThirdComponent'"> 
    <app-third-component></app-third-component> 
</ng-container> 

manager.component.ts應該有一個輸入:

import { Component, OnInit, Input } from '@angular/core'; 

@Component({ 
selector: 'app-manager', 
templateUrl: './manager.component.html', 
styleUrls: ['./manager.component.css'] 
}) 
export class ManagerComponent implements OnInit { 

    @Input() component: string; 

    constructor() { } 

    ngOnInit() { 
    } 

} 

在您的app.component.ts中,您將數據傳遞給數組:

// app.component.ts 

data: Any[] = []; 

ngOnInit() { 
    this.getWidget() 
     .subscribe(
     data => { 
      this.data = data; 
     }, 
     error => { 
      ??? 
     } 
    ); 
} 

getWidget() { 
    return this.http.get('www.api.com'); 
} 

最後,在app.component.html你叫*ngFor它迭代數據,並通過type到管理器組件:

<ng-container *ngFor='let d of data'> 
    <app-manager [component]="d.type"></app-manager> 
</ng-container>