Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use `templateref` from other Angular component?

Tags:

angular

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.

like image 861
Boo Yan Jiong Avatar asked Oct 30 '18 15:10

Boo Yan Jiong


1 Answers

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.

like image 56
ibenjelloun Avatar answered Oct 13 '22 10:10

ibenjelloun