如何使用来自其他 Angular 组件的`templateref`?

Boo*_*ong 5 angular

如何templateRef从其他组件模板文件中使用?

我有BatmanComponentSpidermanComponent还有一个JokerComponent。其中一些具有类似的功能,因此我决定创建一个HumanComponent, 并将所有可重用的 HTML 代码放在该文件中,如下所示:

注意:HumanComponent永远不会使用,它只是一个包含所有默认模板的文件。

<!-- human.component.ts -->
<ng-template #eye>
    Eyes: {{ size }}
</ng-template>
<ng-template #body>
    Body: bust {{ x[0] }}, waist {{ x[1] }}, hip {{ x[2] }} 
</ng-template>
Run Code Online (Sandbox Code Playgroud)

我可以知道如何注入这些模板(来自human.component.ts)并在batman.component.ts.... 中使用它吗?

我知道我可以这样做:(仅模板代码被复制粘贴到蝙蝠侠、蜘蛛侠和小丑HTML 文件中时)

<!-- batman.component.ts -->
<ng-container *ngTemplateOutlet="eye; context: contextObj"></ng-container>

<ng-template #eye> ... </ng-template> <!-- need to copy/paste here, and use it locally -->
Run Code Online (Sandbox Code Playgroud)

我可以知道如何导出 templateRef到其他文件并重新使用它们吗?我不想在这些文件中复制和粘贴类似的代码,我希望我可以有一个默认的模板文件,然后将这些代码导出给任何想要它的人。是否可以?


更新:

阅读评论后,我决定使用可重用组件而不是这种“技术”......可能,Angular 团队正在努力优化可重用组件方法(如@artyom、@rafael、@ibenjelloun 建议的那样),然后可能跟着他们的路走会更聪明……哈哈……

不管怎样,谢谢。

ibe*_*oun 8

如果您创建一个TemplatesService,您可以在其中注册您的模板并在其他组件中使用它们:

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

@Injectable({
  providedIn: 'root'
})
export class TemplatesService {
  templates = {};
  add(name: string, ref) {
    this.templates[name] = ref; 
  }
  get(name: string) {
    return this.templates[name];
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以从根组件将模板添加到服务中:

{{ _templatesService.add('template1', template1) }}
{{ _templatesService.add('template2', template2) }}

<ng-template #template1 let-name="name">
  ****** Template 1 {{name}} ******
</ng-template>

<ng-template #template2 let-name="name">
  ----- Template 2 {{name}} ------
</ng-template>
Run Code Online (Sandbox Code Playgroud)

并在另一个组件中使用它们:

<ng-container *ngTemplateOutlet="_templatesService.get('template1'); 
 context: {name: 'From Hello Component'}"></ng-container>
Run Code Online (Sandbox Code Playgroud)

这是一个 stackblitz 演示。

  • 我看不到我会使用这个 hack 的情况。对于您的问题,我将创建一个组件,这就是它的用途和优化目的。如果您想让组件包含不断变化的模板,那么使用模板将是一个好主意,该组件会将模板作为输入。 (2认同)