【问题标题】:Repeat ng-template with ng-content as body (create copy of ng-content)以 ng-content 作为正文重复 ng-template(创建 ng-content 的副本)
【发布时间】:2019-04-04 07:26:16
【问题描述】:

我正在创建一个将自定义列添加到 PrimeNg 表的选项。我想创建它的原因是因为我提供了一个默认表,其中已经设置了很多配置选项。

我遇到的问题是我似乎无法多次重复 ng-template 组件。


我的版本

  • 7.2.12
  • 初萌7.1.0
  • @角/动画7.2.12

我想达到什么目的

我想创建一个包装器来简化列的创建,并消除在表格主体中创建多个模板的需要。

我想简化的例子:

<table>
 <!-- Row 1 -->
 <ng-template #header><th>edit></th></ng-template>
 <ng-template #content><button>edit></button></ng-template>

 <!-- Row 2 -->
 <ng-template #header><th>delete></th></ng-template>
 <ng-template #content><button>delete></button></ng-template>
</table>

我想简化为:

<table>
  <!-- Row 1 -->
  <custom-column>
    <th header>edit></th>
    <button>edit></button>
  </custom-column>

  <!-- Row 2 -->
  <custom-column>
    <th header>delete></th>
    <button>delete></button>
  </custom-column>
</table>

我几乎可以在 StackBlitz 中完成这项工作


问题

我现在面临的问题是我需要为表格中的每一行重复内容模板,以便每一行都有一个编辑和一个删除按钮。但是通过这种设置,按钮只显示在最后一行(我认为这是因为ng-content 只包含一次?)。

我想要实现的目标是否可行,如果可以,我应该如何更改我的代码?

【问题讨论】:

  • 实际上它在每次迭代时都包含在内,(如您所见的绑定 cmets),但它仅在最后一次迭代中被投影。

标签: angular typescript primeng transclusion


【解决方案1】:

由于ng-content 组件不支持多次投影相同的内容(herehere),我需要切换到将模板注入到表格组件中。

受到 Primeng 解决此问题的方式的启发(通过创建包含模板的指令):

@Directive({ selector: '[pTemplate]' })
export class PrimeTemplate {

  @Input() type: string;

  @Input('pTemplate') name: string;

  constructor(public template: TemplateRef<any>) { }

  getType(): string {
    return this.name;
  }
}

用法:&lt;ng-template pTemplate="header"&gt;&lt;/ng-template

他们正在创建一个模板并在表格组件中获取对该模板的引用。模板可以无限次重复使用,从而解决投影问题。


因为我想保持灵活性,但又想避免使用字符串比较(注意“名称”属性)以及需要从 querylist 中提取正确的模板,所以我最终创建了 2 个可以使用的指令如下(与我第一次尝试的示例相同,但实现更好):

<ng-container>
  <ng-template appColHeader>Delete</ng-template>
  <ng-template appColContent><button>Not here!</button></ng-template>
</ng-container> 

这段代码的完整实现可以在StackBlitz找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2021-12-15
    相关资源
    最近更新 更多