Passing for variable to ng-content

前端 未结 1 811
花落未央
花落未央 2021-01-02 11:28

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

Example, the containing-component:

相关标签:
1条回答
  • 2021-01-02 12:19

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

    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>
    

    Or use 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>
    
    0 讨论(0)
提交回复
热议问题