2017-08-24 63 views
0

我想在父組件的模板中有條件地顯示子組件(包括其ContentChildren)。有條件地在父組件中顯示子組件及其內容

app.component.html

<parent> 
    <child #initial> 
    <span>Player</span> 
    </child> 
    <child label="Intro"> 
    <span>Intro</span> 
    </child> 
    <child label="Content"> 
    <span>Content</span> 
    </child> 
</tabs> 

期望結果

<parent> 
    <child> 
    <span>Player</span> 
    </child> 
</parent> 

parent.component.ts

@Component({ 
    selector: 'parent', 
    template: `<!--Display {{current}} and its ContentChildren-->`, 
    styleUrls: ['./tabs.component.scss'] 
}) 

export class ParentComponent implements OnInit { 
    @ContentChildren(ChildComponent) childs; 
    @ContentChild("initial") initial; 
    @ContentChild("open") current; 
    ngOnInit(): void { 
    if (this.initial) this.current = this.initial; 
    } 
} 

個child.component.ts

@Component({ 
    selector: 'child', 
    template: `<ng-content></ng-content>`, 
}) 

export class ChildComponent { 
    @Input() label: string; 
} 

嘗試爲parent.component.html

<ng-container *ngFor="let child in childs"> 
    <child *ngIf="child == current"></child> //ContentChildren as defined in 'app.component.html' are lost now 
</ng-container> 
+0

@Vega是的,沒錯 –

+0

,你不希望使用ngif或ngswitch ..? – Vega

+0

@Vega它有效巫婆ngIf,但子組件的丟失 –

回答

0

您可以通過使用ngSwitch做。

<parent> 
    <div [ngSwitch]="current"> 
     <child1 *ngSwitchCase="'Intro'" label="Intro"> 
      <span>Intro</span> 
     </child1> 

     <child2 *ngSwitchCase="'Content'" label="Content"> 
      <span>Content</span> 
     </child2> 
    </div> 
</parent> 

如果您不希望ngSwitch和需要動態改變整個模板做的,希望下面的答案將有助於 Dynamic template URLs in Angular 2 Ask

+0

問題在於,子組件的現在是靜態的,但它必須是動態的。 –

+0

@Michel酷如果您需要動態更改,鏈接的答案可能會有用 – Rajez