html - 迭代 ng-content 项目并将每个项目包装在它自己的嵌套 div 中

标签 html angular angular6 ng-content

我读到这还不受支持,但我想知道是否有人想出了解决此问题的 hacky 解决方法。

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

<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>

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

谢谢!

最佳答案

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

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>

关于html - 迭代 ng-content 项目并将每个项目包装在它自己的嵌套 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52597559/

相关文章:

javascript - 我怎样才能在这里制作一个 html 解决方案而不是使用 javascript hack?

javascript - 从数据列表中动态删除项目

angular - amcharts 堆叠条形图 - 响应事件突出显示值(更改 alpha)

node.js - 如何在 Angular 应用程序中显示 Node js api 错误

html - 可以在组件的 html 中使用 id 属性吗?

javascript - jQuery 迭代 .each() 并根据第一个 .each() 给出迭代 id

JavaScript 选择 HTMLInputElement 在我没想到的时候起作用了

angular - 如何在 Angular 中实现 Facebook 像素?

css - Angular 6 如何在指令中添加多个样式?样式元素未与指令 (addClass) 连接

html - 如何选择 Angular 6 中的所有复选框?