首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将变量传递给ng-content

将变量传递给ng-content
EN

Stack Overflow用户
提问于 2018-08-12 16:45:13
回答 1查看 9.2K关注 0票数 10

如何将ngFor变量传递给ng-content模板。

例如,containing-component:

代码语言:javascript
复制
<ul>
    <li *ngFor="let item of itemsArray">
       <ng-content></ng-content>
    </li>
</ul>

嵌套的content-component:

代码语言:javascript
复制
<div>
    <span *ngIf="item.type_one"></span>
    <span *ngIf="item.type_two"></span>
</div>

例如,两者都有:

代码语言:javascript
复制
<containing-component>
    <content-component>
    </content-component>
</containing-component>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-12 19:38:39

您不能将ng-content用作动态模板。请改用ng-template

代码语言:javascript
复制
<ul>
    <li *ngFor="let item of itemsArray">
       <ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item  }">
       </ng-container>
    </li>
</ul>
代码语言:javascript
复制
export class ContainingComponent {

  ...

  @ContentChild(TemplateRef, {static: true}) 
  @Input() itemTemplate: TemplateRef<any>;
}

因此您可以将动态模板引用到containing-component中。在这种情况下,您可以在content-component上包装ng-template

代码语言:javascript
复制
<containing-component [itemTemplate]="itemTmpl">
</containing-component>

<ng-template #itemTmpl let-data>

    <content-component
      [item]="data">
    </content-component>
</ng-template>

或者使用ng-template directly

代码语言:javascript
复制
<containing-component 
   [itemTemplate]="itemTmpl"
   [itemArray]="items">
</containing-component>

<ng-template #itemTmpl let-data>
  <div>
    <span *ngIf="data.type_one"></span>
    <span *ngIf="data.type_two"></span>
  </div>
</ng-template>
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51807192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档