2017-01-23 60 views
0

我正在构建一个容器,其中包含一个标题和一个内容。我可以通过点击标题切换容器并显示我的内容。在我的头文件中还有一些信息,这些信息在每个切换状态中都可见。它看起来像这样:在同一组件中使用ng-transclude不止一次

封闭(只头的东西):

enter image description here

打开(标题和内容的东西):

enter image description here

我用角组件来构建这样的:

myContainer.ts:

/** @ngInject */ 
export class MyContainer extends Controller { 
    static componentName = 'myContainer'; 
    static templateUrl = 'app/comp/components/myContainer/myContainer.html'; 

    static componentOptions: ng.IComponentOptions = { 
     transclude: true, 
     bindings: { 
      headerTitle: '@' 
     } 
    }; 

    headerTitle: string; 
    isShownBlock: boolean = false; 

    constructor(

    ) { 
     super(); 
    } 
} 

myContainer.html:

<div class="containerHeader" ng-click="ctrl.isShownBlock = !ctrl.isShownBlock"> 
    <my-icon icon="arrow-filled"></my-icon> 
    <div class="containerTitle">{{ctrl.headerTitle}}</div> 
</div> 
<div class="containerContent" ng-if="ctrl.isShownBlock"> 
    <div class="containerInnerContent" ng-transclude> 
     <!--TRANSCLUDED_CONTENT--> 
    </div> 
</div> 

在我的代码使用myContainer中:

<my-container header-title="my container"> 
    transcluded things 
</my-container> 

正如你所看到的,我使用的是binding设置我的容器标题和将我的内容填入ng-transclude。现在我想将我的容器标题设置为ng-transclude。我的问题是,我不知道如何区分我的标题和我的内容transcluded的东西?我试图为标题创建一个自己的组件,并将其放在<my-container></my-container>内,并使用ng-transclude,但我没有得到最终解决方案。我希望这很清楚,有什么想法?

回答

0

我发现这个页面上的解决方案:https://blog.thoughtram.io/angular/2015/11/16/multiple-transclusion-and-named-slots.html

我可以使用多个ng-transclude-slots。我只需要将transclude: true更改为object。在这个对象中,我可以把我的插槽放在他们来自哪里。我现在也可以删除我的标题标题的绑定。所以basicly它看起来像这样:

myContainer.ts: 我已经改变了transclude: trueobject有两个插槽,我的头和我的内容。我现在也可以删除我的绑定,因为它不再需要。

/** @ngInject */ 
export class MyContainer extends Controller { 
    static componentName = 'myContainer'; 
    static templateUrl = 'app/comp/components/myContainer/myContainer.html'; 

    static componentOptions: any = { 
     transclude: { 
      headerSlot: 'headerTitle', 
      contentSlot: 'contentData' 
     } 
    }; 

    isShownBlock: boolean = false; 

    constructor(

    ) { 
     super(); 
    } 
} 

myContainer.html: 在我的模板我实现了两个div的,在我的transclude应与标题和内容槽的名字命名的,所以我可以处理其中的数据应该是transcluded。

<div class="containerHeader" ng-click="ctrl.isShownBlock = !ctrl.isShownBlock"> 
    <my-icon icon="arrow-filled"></my-icon> 
    <div class="containerTitle" ng-transclude="headerSlot"></div> 
</div> 
<div class="containerContent" ng-if="ctrl.isShownBlock"> 
    <div class="containerInnerContent" ng-transclude="contentSlot"></div> 
</div> 

在我的代码使用myContainer中: 在我的成分标签,我实现了两个变量与我的对象的插槽名称。内部的代码会被截断。

<my-container> 
    <header-title>Title</header-title> 
    <content-data>Content</content-data> 
</my-container> 

现在它工作正常。干杯。

相关问题