2016-04-24 50 views
0

我在學Angular 2. 我用下面的模板創建了一個組件。根據狀態顯示不同的組件?

<h1>My component</h1> 
<placeholder?></placeholder?> 

根據在我的組件我想顯示不同的子部件,而不是佔位符標記的狀態。那可能嗎?怎麼樣?

例如:假設我已將一項服務注入到我的組件中。如果此服務返回1,我想要顯示ComponentOne和服務中的所有其他值,我想顯示OtherComponent。

回答

0

使用* ngIf您要顯示或不每個組件:

<component1 *ngIf="service.value1"></component1> 

<component2 *ngIf="service.value2"></component2> 
0

我會建議使用*ngIf與動態組件裝載沿着應用的條件。 你也可以關注這個plnkr以獲取更多參考。

Dynamic Component Loader Example

所有你需要做的是對的div應用*ngIf指示要加載的組件。

例如,

//our root app component 
import {Component, View, DynamicComponentLoader, ElementRef } from 'angular2/angular2' 

@Component({ 
    selector: 'dc', 
    template: '<b>Some template</b>' 
}) 

class DynamicComponent {} 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div *ngIf="your condition"> 
     <div #container></div> 
    </div> 
    ` 
}) 

export class App { 
    dynamicComponentLoader: DynamicComponentLoader; 
    constructor(dynamicComponentLoader: DynamicComponentLoader, elementRef: ElementRef) { 
    this.dynamicComponentLoader = dynamicComponentLoader; 
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container'); 

    } 

} 
相關問題