【问题标题】:Angular `ng-content` is not working as expected with primeNg tablesAngular `ng-content` 在 primeNg 表中没有按预期工作
【发布时间】:2019-04-12 17:14:54
【问题描述】:

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

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

我尝试直接在table.component.html 中添加thtbody,它会显示表格。 ng-content 不应该因为内容具有相同的 html 而做同样的事情吗?

这里是带有示例的 sn-p 的链接。检查共享目录下的table.component.htmlapp.component.html 用于初始启动。注释 ng-content 行并取消注释 table.component.html 中的其余行,您应该会看到该表。 https://stackblitz.com/edit/angular-playground-kwudxn?file=app%2Fshared%2Ftable%2Ftable.component.html

【问题讨论】:

  • 嗨 - 您的来源似乎不是工作版本 - 请检查一下,请检查一下

标签: angular primeng primeng-turbotable


【解决方案1】:

您的应用程序的问题是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。

【讨论】:

  • 这正是我在发布答案之前尝试过的,好方法:) +1
  • 但我不得不承认,我试图先加载模板,然后懒惰地从组件中强制实例化p-table
【解决方案2】:

ng-content 基本上是用于content projection. 尝试使用&lt;ng-template&gt; 而不是&lt;ng-content&gt;

链接:-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/app.component.html

 <child>
    <p>My <i>projected</i> content.</p>
  </child>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 2017-08-20
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多