如何templateRef从其他组件模板文件中使用?
我有BatmanComponent,SpidermanComponent还有一个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 建议的那样),然后可能跟着他们的路走会更聪明……哈哈……
不管怎样,谢谢。
如果您创建一个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)
| 归档时间: |
|
| 查看次数: |
1732 次 |
| 最近记录: |