【问题标题】:Iterate over ng-content items and wrap each in it's own nested div迭代 ng-content 项目并将每个项目包装在它自己的嵌套 div 中
【发布时间】:2019-03-06 22:39:19
【问题描述】:

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

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

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

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

谢谢!

【问题讨论】:

  • 你有没有找到方法?

标签: html angular angular6 ng-content


【解决方案1】:

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

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

父组件.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;
}

父组件.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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 此解决方案将不起作用,因为我从 获取按钮列表并且不容易获得。
    • 有点,我也建议改变你的架构。但是如果你真的需要使用 ng-content 运行,你可能可以使用 ViewChildren 或 ContentChildren 捕获它们并在父组件能够读取它们之后进行管理
    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2018-02-06
    相关资源
    最近更新 更多