6

我读过这还不被支持,但我想知道是否有人想出了一个解决这个问题的方法。

我目前拥有的是具有此模板的父组件:

<dxi-item location='after' class="osii-item-content">
    <span><ng-content select="[osii-page-button]"></ng-content></span>
</dxi-item>

这正在创建以下内容:

<dxi-item location='after' class="osii-item-content">
    <button> // first button returned by ng-content </button>
    <button> // second button returned by ng-content </button>
    <button> // third button returned by ng-content </button>
</dxi-item>

但我想要它做的是获取以下 html:

<dxi-item location='after' class="osii-item-content">
    <button> // first button returned by ng-content </button>
</dxi-item> 

<dxi-item location='after' class="osii-item-content">
    <button> // second button returned by ng-content </button>
</dxi-item>

<dxi-item location='after' class="osii-item-content">
    <button> // third button returned by ng-content </button>
</dxi-item>

此问题是否有任何已知的解决方法?

谢谢!

4

2 回答 2

3

作为装备,您可以将所有按钮放在父组件内容中的模板中,然后遍历所有模板以将它们显示为内容。

App.component.html

<parent_component>
    <ng-template>
        <button> // first button </button>
    </ng-template>
    <ng-template>
        <button> // second button </button>
    </ng-template>
    <ng-template>
        <button> // third button </button>
    </ng-template>
</parent_component>

父组件.ts

export class ParentComponent {
  @ContentChildren(TemplateRef) templateRefs: QueryList<TemplateRef>;
}

Parent.component.html

<div *ngFor="let x of templateRefs">
  <dxi-item location='after' class="osii-item-content"> 
    <ng-container *ngTemplateOutlet="x"></ng-container>
  </dxi-item>
</div>

更好的解决方案(这不是您所要求的)是为您的按钮传递一个模板,然后传递一个包含按钮内容的数组。在示例中,我传递了一个字符串数组,但它当然可以是整个对象。

App.component.html

<parent_component [texts]=['first', 'second', 'third'>
    <ng-template let-x @BtnTemplate>
        <button> {{x}} </button>
    </ng-template>
</parent_compnent>

父组件.ts

export class ParentComponent {
  @Input() texts: string[];
  @ContentChild("BtnTemplate") btnTemplateRef: TemplateRef;
}

Parent.component.html

<div *ngFor="let x of texts">
  <dxi-item location='after' class="osii-item-content"> 
    <ng-container *ngTemplateOutlet="btnTemplateRef"
                  context: { $implicit: x }">
    </ng-container>
  </dxi-item>
</div>
于 2018-10-01T20:18:37.873 回答
0

我猜你正在寻找的是这样的: <ng-container *ngFor="let item of items"> <your-compo></your-compo> </ng-container> 所以你迭代项目并生成所需的组件。别担心,ng-container 不会被渲染,只有你的组件会被渲染。

于 2018-10-01T19:45:37.810 回答