2017-04-26 14 views
4

私はAngularでサイズ変更可能なパネルシステムを構築しようとしています。 したがって、複数のコンテナを、ユーザーがサイズ変更できるバーで区切ることができます。私は、このHTMLコードを記述するために、開発者が必要となるソリューションを持っている瞬間のために角度 - 別のコンポーネントの後ろにコードを追加します。

<split-pane> 
    <container>Some content</container> 
    <separator></separator> 
    <container>Another content</container> 
    <separator></separtor> 
    <container>Content ?</container> 
<split-pane> 

分割ペインコンテナセパレーターは、すべてのカスタムangular2コンポーネントです。 分割ペインのテンプレートはちょうど

<ng-content></ng-content> 

であると私は、このソリューションを持っているコンテナsepartor内の分割ペイン@ContentChildren(ContainerComponent)を使用して@ContentChildren(SeparatorComponent)

問題は、その開発者に対しあるアクセスすべてのコンテナに手動でセパレータを追加する必要があります。

<split-pane> 
    <container>Some content</container> 
    <container>Another content</container> 
    <container>Content ?</container> 
<split-pane> 

をそしてセパレーターコンポーネントが自動的に追加されます:

私は必要なHTMLのようになります解決策を持っているしたいと思います。 しかし、Angularでこれを行う方法はわかりません。 Transclusionはこれに近づく方法だと思われますが、私はその周りを頭で覆うことはできません。

おかげ

答えて

3

我々が最初に私たちはこのような私たちのダイナミックな構成要素についての角度コンパイラを言うために必要なすべての動的ので、何かをロードする必要がある場合:

... 
    entryComponents: [SeparatorComponent] 
}) 
export class AppModule {} 

だから、私たちの希望のテンプレートは次のようになります。

<split-pane> 
    <container>Some content</container> 
    <container>Another content</container> 
    <container>Content ?</container> 
</split-pane> 

container要素に何かを追加するには、のそれぞれに対してViewContainerRefを取得する必要があります。 10。私は次のようにSplitPaneComponent

@ContentChildren(ContainerComponent, { read: ViewContainerRef }) containersRefs: QueryList<ViewContainerRef>; 

それを行うだろうそれからちょうど部品の工場を取得するためにComponentFactoryResolverを使用してSeparatorComponentcontainer後のタグを追加するViewContainersの上に受け取りました。これは、ご希望の構文と一致していませんが、ngForを使用して、コードを短くすることができるかもしれ

ngAfterContentInit() { 
    this.containersRefs.forEach((vcRef: ViewContainerRef, index: number, arr: any[]) => { 
    if(index === arr.length - 1) { 
     return; 
    } 

    let compFactory = this.resolver.resolveComponentFactory(SeparatorComponent); 
    let compRef = vcRef.createComponent(compFactory); 
    this.separators.push(compRef); 
    }) 
} 

Plunker Example

+0

正確に私が必要としたもの。プランナーに感謝します! – cpaulus

+0

喜んで助けてください! :) – yurzui

1

:それはのようになりますようです。

lastngForを組み合わせる:

<template ngFor let-item [ngForOf]="items" let-i="index" let-last="last"> 
    <container>{{item.content}}</container> 
    <separator *ngIf="!last"></separator> 
</template> 

を、それがデータを取得することができますので、コンポーネントクラスでitemsを定義します。

+0

コンテナの内容が別のコンポーネントである可能性があるので、これはうまくいかないと思います。 – cpaulus

関連する問題