How to use templateRef
from other component template file?
I have BatmanComponent
, SpidermanComponent
and a JokerComponent
. Some of them have similar features, so that I decided to create a HumanComponent
, and put all reusable HTML codes in that file, as such:
Note: the HumanComponent
will never be used, it is just a file that consists all default template.
<!-- 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>
May I know how to inject those template (from human.component.ts) and use it inside the batman.component.ts
, etc...?
I know I can do it as such: (only if the template code is being copy-paste inside the batman, spiderman, and joker HTML files)
<!-- 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 -->
May I know how can I export templateRef
to other files, and re-use them? I don't want to copy and paste similar codes across those files, I hope I can have a default template file, and just export those codes to whoever want it. Is it possible?
Update:
After reading the comments, I decided to use the reusable component rather than this "techniques"... Probably, the Angular team is trying hard to optimize the reusable component approach (as @artyom, @rafael, @ibenjelloun suggested), then probably just follow their path will be wiser... Haha...
Anyway, thanks.
If you create a TemplatesService
, you can register your templates in it and use them in other components :
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];
}
}
You can then add your templates to the service from a root component :
{{ _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>
And use them in another component :
<ng-container *ngTemplateOutlet="_templatesService.get('template1');
context: {name: 'From Hello Component'}"></ng-container>
Here is a stackblitz demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With