繁体   English   中英

使用无模板标签在 Angular 中托管递归组件

[英]Use a template-free tag to host a Recursive Component in Angular

我在 Angular 中创建了一个递归组件my-row ,这意味着它对我的树数据结构的每一级都调用了多次,

组件my-row的模板:

<ng-container [pReorderableRow]="rowIndex" *ngIf="level === this.groupingLevels.length else child_row">
    <tr>
       <td [attr.rowspan]="rowGroupMetaData.indexes.length"> 
           {{rowGroupMetaData.source[col]}}
       </td>
    </tr>
</ng-container>


<ng-template #child_row>
  <my-row  *ngFor="let metaKey of getKeys(); index as i;"
          [rowGroupMetaData]="rowGroupMetaData.children[metaKey]"
  >
  </my-row>
</ng-template>

我在我的桌子的身体里叫它如下:

<p-table
    [value]="[{}]"
    [columns]="cols"
    [reorderableColumns]="true"
    (onColReorder)="onColReorder($event)"
  >
    <ng-template pTemplate="header" let-columns>
      <tr>
        <th>
          {{col}}
        </th>
      </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowIndex="rowIndex" let-columns>
      <my-row *ngFor="let metaKey of getKeys(rowGroupMetadata)"
                  [rowGroupMetaData]="rowGroupMetadata[metaKey]"></my-row>
    </ng-template>
</p-table>

问题是我不能在 tbody 和它的 tr 之间放置任何标签,否则它不会出现,但我可以在它们之间使用ng-containerng-template ,因为它们不会影响结构。

在发现我试图将我的组件作为ng-container / ng-template中的指令托管后:

<ng-container my-row
                  *ngFor="let metaKey of getKeys(rowGroupMetadata)"
                  [rowGroupMetaData]="rowGroupMetadata[metaKey]"
></ng-container>

但不幸的是,我有错误说ng-container没有用作主机,也没有ng-template

您能否提供一些我可以用于托管或其他解决方案的其他潜在组件。

您可以尝试以下方法

在 MyRowComponent 中更改 Component 装饰器中的选择器,以便它允许您使用类似于指令的组件

@Component({
  selector: '[my-row]', // instead of just 'my-row'
  templateUrl: './my-row.component.html',
})

在表格的正文中进行以下更改:

<ng-template pTemplate="body" let-rowIndex="rowIndex" let-columns>
      // host my-row directly on a tr element
      <tr my-row *ngFor="let metaKey of getKeys(rowGroupMetadata)"
                  [rowGroupMetaData]="rowGroupMetadata[metaKey]"></tr>
</ng-template>

在 my-row 的模板中

<ng-container [pReorderableRow]="rowIndex" *ngIf="level === this.groupingLevels.length else child_row">
   
   // if not child element, only show td as the host element is tr itself

   <td [attr.rowspan]="rowGroupMetaData.indexes.length"> 
       {{rowGroupMetaData.source[col]}}
   </td>
   
</ng-container>


<ng-template #child_row>
  <tr my-row  *ngFor="let metaKey of getKeys(); index as i;"
          [rowGroupMetaData]="rowGroupMetaData.children[metaKey]"
  >
  </tr my-row>
</ng-template>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM