首页 > 解决方案 > 角度 7 中的多个 NgTemplate

问题描述

我有 Angular 7 项目。我写了<ng-template>,它正在发送我的rowData. 当我ng-template像下面这样写一个时,一切都运行良好。但是,我需要多个 ng-template。我尝试了类似下面的方法。但是,我无法执行。我怎样才能做到这一点?




这完美地工作

app.grid.component.html

<ng-template pTemplate="body" let-rowData>
  <tr>
    <td *ngFor="let col of Columns" class="ui-resizable-column">
      <span>{{rowData[col.field]}}</span>
    </td>
    <td>
      <ng-template *ngTemplateOutlet="templateRef; context : {rowData : rowData}"></ng-template>
    </td>
  </tr>
</ng-template>

app.grid.component.ts

export class GridComponent implements OnInit {
    @ContentChild(TemplateRef) templateRef: TemplateRef<any>;
  }

我的组件.html

 <app-grid>
   <ng-template let-rowData="rowData">
       <button type="button" label="Update" (click)="update(rowData)"
   </ng-template>
 </app-grid>



但我想要像下面这样的多个

app.grid.component.html

<ng-template pTemplate="body" let-rowData>
  <tr>
    <td *ngFor="let col of Columns" class="ui-resizable-column">
      <span>{{rowData[col.field]}}</span>
    </td>
    <td>
      <ng-template *ngTemplateOutlet="templateRef; context : {rowData : rowData}"></ng-template>
    </td>
    <td>
      <ng-template *ngTemplateOutlet="templateRef2; context : {rowData : rowData}"></ng-template>
    </td>
  </tr>
</ng-template>

app.grid.component.ts

export class GridComponent implements OnInit {
    @ContentChild(TemplateRef) templateRef: TemplateRef<any>;
    @ContentChild(TemplateRef) templateRef2: TemplateRef<any>;
  }

我的组件.html

 <app-grid>
   <ng-template let-rowData="rowData" [ngForTemplate]="templateRef">
       <button type="button" label="Delete" (click)="delete(rowData)"></button>
   </ng-template>
   <ng-template let-rowData="rowData" [ngForTemplate]="templateRef2">
       <button type="button" label="Update" (click)="update(rowData)"></button>
   </ng-template>
 </app-grid>

标签: angulartypescriptangular7

解决方案


我找到了答案。你可以从这个 stackblitz 链接中看到。(这个堆栈闪电战并不完全相同。但逻辑完全一样。)

堆栈闪电战


推荐阅读