【问题标题】:content project elements through directive and <ng-template> in angular 13通过指令和 angular 13 中的 <ng-template> 内容项目元素
【发布时间】:2022-12-03 00:08:47
【问题描述】:

我有以下情况:

页面.component.html

<app-component-w-directive>
  <child-component></child-component>
</app-component-w-directive>

组件-w-directive.component.html

<ng-template
  myCustomDirective
  [someInputs]="someValues"
  [someInputs]="someValues"
  [someInputs]="someValues"
>
  <!-- my failed attempt -->
  <ng-content></ng-content>
</ng-template>

我使用 component-w-directive 组件根据一些信息动态地转换不同的组件,我希望它们都共享来自 page.component.html 的相同的 &lt;child-component&gt;

目前,在component-w-directive.component 内,我可以完全访问&lt;child-component&gt;。并尝试执行以下操作以将 ng-content 深入到使用指令动态生成的组件之一,但没有成功,在任何“可转换”组件中,它都未定义 ng-content。

casted-from-directive.component.html

<!-- some html -->

  <ng-content></ng-content>
  <!-- (expected to be the child-component from page.component.html) -->

<!-- some html -->

我如何通过指令将 &lt;child-component&gt; 投影到动态生成的代码中?

编辑:这是一个例子https://stackblitz.com/edit/angular-ivy-qgbslk

【问题讨论】:

  • 你能尝试在 stackblitz 上创建一个样本吗?
  • 当然!我刚刚添加了它
  • 您可以更改 MyComponent 接口以包含模板引用吗?
  • 当然,如果需要,您可以分叉项目并更改所有内容

标签: angular angular13 ng-template ng-content angular-content-projection


【解决方案1】:

我没有为任何组件找到一种优雅的方式,所以只有当你可以访问注入的组件时它才会起作用(今天,明天)

  1. 您需要更改此组件以及 MyComponent 接口 TodayComponent HTML:
    <ng-container *ngTemplateOutlet="content"></ng-container>
    

    TodayComponent.ts

    content?: TemplateRef<any>;
    
    1. 现在我们需要将相同的输入添加到创建指令并将其传递给创建组件
     @Input() contentTemplate: TemplateRef<any>;
    ...
    
      this.cmpRef = this.viewContainerRef.createComponent<MyComponent>(component);
      this.cmpRef.instance.content = this.contentTemplate;
    
    1. 最后一步是在 Hook 组件和指令之间建立桥梁。请注意,我们需要将 ng-content 包装到 ng-template 中并将其作为 ref 传递给创建指令。
    <ng-container
      appDynamicComponent
      [compSelector]="compSelector"
      [color]="color"
      [contentTemplate]="content"
    ></ng-container>
    
    <ng-template #content>
      <ng-content></ng-content>
    </ng-template>
    
    1. Working sample

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 1970-01-01
    • 2022-01-26
    • 2016-07-09
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    相关资源
    最近更新 更多