本文介绍了将变量传递给ng-content的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I pass an ngFor variable to the ng-content template.

示例,包含组件:

<ul>
    <li *ngFor="let item of itemsArray">
       <ng-content></ng-content>
    </li>
</ul>

嵌套的内容组件:

<div>
    <span *ngIf="item.type_one"></span>
    <span *ngIf="item.type_two"></span>
</div>

示例,两者:

<containing-component>
    <content-component>
    </content-component>
</containing-component>

推荐答案

您不能将ng-content用作动态模板.使用ng-template代替

You can not use ng-content as dynamic template. Use ng-template instead

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

  ...

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

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

So you can reference dynamic template into containing-component. In this case, you can wrap ng-template over content-component

<containing-component [itemTemplate]="itemTmpl">
</containing-component>

<ng-template #itemTmpl let-data>

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

或使用ng-template directly:

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

这篇关于将变量传递给ng-content的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:21