2

我正在处理实现自定义表并遇到问题。

我无法在表格组件中正确投影列组件内容。

  • table.component.ts

    @Component({
        selector: 'app-table',
        template: `
        <table>
        ...
        <tbody>
            <tr
                *ngFor="let row of rows; let i = index">
                <td *ngFor="let column of columns">
                    <ng-container *ngIf="column.key">{{ getCellValue(column.key, row.value) }}</ng-container>
                    <ng-container *ngIf="!column.key">
                        <ng-content select="app-column"></ng-content> <!-- [1] this one show content just in last cell -->
    
                        <ng-container *ngTemplateOutlet="column.contentTemplateRef;"></ng-container> <!-- [2] the same as line above, but another column wrapped in ng-template -->
                    </ng-container>
                </td>
            </tr>
        </tbody>
        ...
        </table>
        `,
        encapsulation: ViewEncapsulation.None,
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class TableComponent implements AfterViewInit, OnDestroy {
        rows: any[];
    
        @ContentChildren(forwardRef(() => TableColumnComponent))
        columns: QueryList<TableColumnComponent>;
    
        getCellValue(key: string, row: any): any {
            return key.split('.').reduce((a, b) => a[b], row);
        }
    
    }
    
  • column.component.ts

    @Component({
        selector: 'app-column',
        template: `<ng-content></ng-content>`, // [1]
        // template: `<ng-template><ng-content></ng-content></ng-template>`, // [2]
        encapsulation: ViewEncapsulation.None,
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class TableColumnComponent {
        @ViewChild(TemplateRef) contentTemplateRef: TemplateRef<any>; // [2]
    }
    

我已经添加了在哪种情况下使用哪个模板的注释。


这个 StackBlitz 示例中,您可以看到它是如何工作的。该按钮仅在最后一列的最后一个单元格中呈现,但我希望最后一列中的所有单元格都将呈现按钮。


我的问题是如何正确呈现列内容?

4

0 回答 0