我想创建一个可重用的表组件,它使用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>
当然,还有其他方法可以实现这一点,例如:您的TableComponent只能有2个@Inputs,只需将它们重新发送到p-table而不是使用PrimeTemplates.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。