3

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 ?

Abel
  • 688
  • 6
  • 19

2 Answers2

1

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.

Vega
  • 27,856
  • 27
  • 95
  • 103
  • Thanks for the quick reply. I like the idea but This will might lead to a mess of flags because I will need one for each subproperties of my object. For example, in my model, the user may or may not have a property age, a property sex, another weight an so on... I must check each of theses subproperties and for each empty property display a dash to prevent an empty string. – Abel Jan 24 '18 at 10:41
  • You can provide the same service to each component, so each component would have its own instance of the service and the flags wont get mixed up. Also you can set an arrray of flags – Vega Jan 24 '18 at 15:08
0

For this specific use case a simpler approach could be: <div>{{user?.name || '-'}}</div>

Abel
  • 688
  • 6
  • 19