2016-06-09 14 views
1

我正在開發一個項目,我需要根據我的端點響應顯示不同的模板/組件。我想根據Angular 2中的不同端點數據顯示不同的組件

例如

{data: {type: 1, textToDisplay: 'I want beans'} } 

應該注入組分1到主應用程序的模板。

如果數據

{data: {type: 2, textToDisplay: 'I want cheese', numberToDisplay: '101' } } 

如果注入組件2到主應用程序模板,當然組件2將組件1,因爲有額外的屬性不同。

我真的不想通過在主應用程序模板中附加元素來使用不良練習,也不想使用[if]指令編寫大量模板,因爲我們可能有許多5-8個不同的組件進行渲染,會膨脹模板。

什麼是合適的方式?

+0

也許類似http://stackoverflow.com/questi ons/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 –

回答

2

正如@君特提到的,你可以使用DynamicComponentLoader

@Component({ 
    selector: 'my-app', 
    template: `<button (click)="addCmp()" #theBody>add</button> 
    `, 
    directives: [BaseDynamicComponent] 
}) 
export class AppComponent { 
    @ViewChild('theBody', {read: ViewContainerRef}) theBody; 
    cmp:ComponentRef; 

    constructor(injector: Injector,private resolver: ComponentResolver) {} 

    addCmp(data){ 
    console.log('adding'); 
    this.resolver.resolveComponent(BaseDynamicComponent).then((factory:ComponentFactory<any>) => { 
     this.cmp = this.theBody.createComponent(factory); 
     //and you can set your BaseDynamicComponent's 'extra' properties here 
     this.cmp.instance.numberToDisplay = data.numberToDisplay; 
    }); 
    } 
    } 

這將增加BaseDynamicComponent的#theBody元素。

下面是一個例子plunkr:

Plunker

如果您單擊添加按鈕,將添加新的組件與分配給「測試」

this.cmp.instance.test = "the test"; 

或者你可以將其試驗場在@Günter的回答(https://stackoverflow.com/a/36325468/5706293)中預定義組件,然後相應地添加它們

+2

DynamicComponentLoader已棄用,請改用ViewContainerRef.createComponent()。看到我上面的鏈接。 –

+2

我看到你已經更新了代碼。如果您不使用它,則不需要注入DynamicComponentLoader ;-) –

+0

@GünterZöchbauer我正在更新它,先生,這是一箇舊模板:D – echonax

相關問題