7

我想创建一个可重用的表格组件,它使用 primeNg 来呈现 ui。我为此创建了一个table.component.html.ts。现在我想为表格呈现内容,这些内容将是表格标题(th)和表格正文(body)。

为此,我正在编写thtbody实现表格的内容,并尝试table.component.html使用<ng-content></ng-content>. 但是表格没有显示。

我尝试直接添加thand并显示表格。不应该因为内容具有相同的 html 而做同样的事情?tbodytable.component.htmlng-content

这是带有示例的片段的链接。检查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

4

2 回答 2

4

您的应用程序的问题是它ng-template不渲染任何东西,所以ng-content也不渲染任何东西。我目前看不到您的任何附加值,TableComponent因为它目前仅重新发送模板,但这可能是因为它只是一个演示,它会在您的情况下具有一些附加值。

您需要更改您TableComponentPrimeTemplate从内容中获取 s 并将它们重新发送到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>

这是完整的分叉 stackblitz 演示。

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

于 2018-11-09T06:54:16.963 回答
0

ng-content基本上用于content projection. Try using<ng-template> 而不是<ng-content>

链接:- https://angular-2-training-book.rangle.io/handout/components/projection.html

app/child/child.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'child',
  template: `
    <div style="border: 1px solid blue; padding: 1rem;">
      <h4>Child Component</h4>
      <ng-content></ng-content>
    </div>
  `
})
export class ChildComponent {
}

应用程序/app.component.html

 <child>
    <p>My <i>projected</i> content.</p>
  </child>
于 2018-11-09T06:47:39.627 回答