首页 > 解决方案 > 在表格中添加动作列,其中动作行来自 ng-content

问题描述

我为可以传递标题和数据的表创建了共享组件,因此我可以在我的多个其他组件中使用它。

现在场景是在一个组件中,我希望Edit在每一行中都有一个按钮,在第二个组件中我想要Active/Inactive单选按钮,所以我使用<ng-content>但它只会添加到表格的最后一行。

这是示例代码: https ://stackblitz.com/edit/angular-ivy-mvcbrk

标签: angular

解决方案


父母经过的孩子只能投影一次(不管有多少<ng-content>)。

所以在这种情况下你必须使用<ng-template>and TemplateRefandContentChild

堆栈闪电战: https ://stackblitz.com/edit/angular-ivy-wuqgtn

像这样

app.component.html

<app-my-table [headers]="headers" [bodies]="bodies">
   <ng-template>
       <button (click)="edit()">Edit</button>
   </ng-template>
</app-my-table>

我的表.component.ts

import { Component, OnInit, Input, TemplateRef, ContentChild } from '@angular/core';

@Component({
    selector: 'app-my-table',
    templateUrl: './my-table.component.html',
    styleUrls: ['./my-table.component.css']
})
export class MyTableComponent implements OnInit {
    @ContentChild(TemplateRef) templateRef: TemplateRef<Element>; // Added this line and its import
    @Input() headers: string[];
    @Input() bodies: string[][];
    constructor() { }

    ngOnInit() {
    }

}

我的表.compnent.html

<td>
    <ng-container [ngTemplateOutlet]="templateRef">
    </ng-container>
    <!-- <ng-content></ng-content> -->
</td>

推荐阅读