加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用primeNg表,Angular`ng-content`无法正常工作

发布时间:2020-12-17 06:56:23 所属栏目:安全 来源:网络整理
导读:我想创建一个可重用的表组件,它使用primeNg来呈现ui.我为此创建了一个table.component.html和.ts.现在我想渲染表格的内容,即表格标题(表格)和表格正文(正文). 为此,我正在编写th和tbody实现作为表的内容,并尝试使用 ng-content / ng-content在table.componen
我想创建一个可重用的表组件,它使用primeNg来呈现ui.我为此创建了一个table.component.html和.ts.现在我想渲染表格的内容,即表格标题(表格)和表格正文(正文).

为此,我正在编写th和tbody实现作为表的内容,并尝试使用< ng-content>< / ng-content>在table.component.html中呈现它.但表格没有显示.

我尝试直接在table.component.html中添加th和tbody,然后显示表格.不应该ng-content做同样的事情,因为内容有相同的HTML?

以下是带有示例的代码段链接.检查共享目录下的table.component.html.和app.component.html初始启动.注释ng-content行并取消注释table.component.html中的剩余行,您应该看到该表.
https://stackblitz.com/edit/angular-playground-kwudxn?file=app%2Fshared%2Ftable%2Ftable.component.html

解决方法

您的应用程序的问题是ng-template不会呈现任何内容,因此ng-content也不会呈现任何内容.我目前在TableComponent中看不到任何附加值,因为它目前只重新发送模板,但这可能是因为它只是一个演示,它会在你的情况下有一些附加价值.

您需要更改TableComponent以从内容中获取PrimeTemplates并将它们重新发送到p-table:

export class TableComponent implements AfterContentInit {

    @Input()
    public data: any[];
    @ContentChildren(PrimeTemplate)
    templates: QueryList<any>;
    headerTemplate: TemplateRef<any>;
    bodyTemplate: TemplateRef<any>;

    constructor() { }

    gePrimeTemplateByType(type: string): PrimeTemplate {
        return this.templates.find(template => {
            return template.getType() === type;
        });
    }

    ngAfterContentInit() {
        this.headerTemplate = this.gePrimeTemplateByType('header').template;
        this.bodyTemplate = this.gePrimeTemplateByType('body').template;
    }
}

在您的模板中:

<p-table [value]="data">
    <ng-template pTemplate="header">
        <ng-container *ngTemplateOutlet="headerTemplate">
        </ng-container>
    </ng-template>
    <ng-template pTemplate="body" let-data>
        <ng-container *ngTemplateOutlet="bodyTemplate; context:{$implicit: data}">
        </ng-container>
    </ng-template>
</p-table>

这里完成forked stackblitz demo.

当然,还有其他方法可以实现这一点,例如:您的TableComponent只能有2个@Inputs,只需将它们重新发送到p-table而不是使用PrimeTemplates.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读