How to render multiple ng-content inside an ngFor loop using Angular 4?

后端 未结 1 430
孤独总比滥情好
孤独总比滥情好 2020-12-07 23:26

I\'m trying to display two differents ng-content inside two ngFor loops. But as described in this answer, Angular can\'t project ng-content multipl

相关标签:
1条回答
  • 2020-12-08 00:02

    The best option in your case would be trancluding ng-template by using ngTemplateOutlet like:

    <app-table [data]="myData">
      <ng-template #lineHeader let-line>
        <div>
         {{line.name}}
        </div>
      </ng-template>
       <ng-template #lineContent let-element>
        <div>
          {{element.name}}
        </div>
       </ng-template>
    </app-table>
    

    app-table.component.ts

    @Component({
      selector: 'app-table',
      template: `
        <div *ngFor="let line of data">
          <ng-container *ngTemplateOutlet="lineHeaderTmpl, 
                         context: { $implicit: line }"></ng-container>
          <div *ngFor="let element of line.values">
            <ng-container *ngTemplateOutlet="lineContentTmpl, 
                           context: { $implicit: element }"></ng-container>
          </div>
        </div>
      `
    })
    export class AppTableComponent  {
      @Input() data: any;
    
      @ContentChild('lineHeader') lineHeaderTmpl: TemplateRef<any>; 
      @ContentChild('lineContent') lineContentTmpl: TemplateRef<any>; 
    }
    

    Stackblitz Example

    0 讨论(0)
提交回复
热议问题