Search code examples
angularng-templatetemplate-variables

Angular, use an external template for ng-template


Let say I have a code like this in a component template :

<div *ngIf="user?.name; else dash-template">{{user?.name}}</div>

And this in another component template :

<div *ngIf="data?.datum; else dash-template">{{data?.datum}}</div>

In both cases, if there is no data, I want to replace my div with a template (dash-template) contained in a ng-template. Right now I'm able to archieve this by adding dash-template in both files.

dash-template code :

<ng-template #dash-template>
  <span>-</span>
</ng-template>

But as soon as I decide to change the content of dash-template, I will need to change every instance of dash-template content in each files.

I tried to include dash-template in a upper component (app.component.html) as well as use a external html file and include it with the link tag in index.html : <head> ... <link rel="import" href="dash.template.html" > ... </head>

But in the first case I did nothing : no error and an empty string displayed. In the second case (with link tag), it can't find the html file.


My questions are :

Is there a way to define an reusable ng-template, or more commonly a reusable template reference variables ?

Is this the right approach to handle empty data ?


Solution

  • My approach is to put a flag in a service, first. From each component, that needs to display that template, check fist for data availability and set that flag accordingly. Then create a new component based on that template. This component would be a child to every other component. Put the whole content under an *ngIf condition based on the flag. Remove "if-else -template" from all components.