1

Lets say we have a service holding mobile: boolean value. Depending on it we display proper TemplateUrl for components which need it.

So it would be something like TemplateUrl: condition ? template_1 : template_2

I can create something similar with require but it won't build for prod properly. When I go to page with it I see null instead of template (only prod).

Angular version 7

Adrian Sawicki
  • 590
  • 5
  • 22
  • In general, this would be solved with a standard html/css setup or angular + flexlayout if you like. the reason why you would run into issues is most probably because of the AOT in prod instead of the JIT for dev. In addition, i have found a similar question: https://stackoverflow.com/questions/49974776/how-to-load-conditionally-templateurl-html-file-in-angular-5-component which also tells it would not be possible as you intend to do it – jcuypers Apr 10 '19 at 21:00
  • I don't think that you can have a conditional `templateUrl`. Assuming that `mobile` is known at runtime, you could put both templates in the same template file, and use `ngIf ... else` to show the appropriate one depending on the condition. – ConnorsFan Apr 10 '19 at 21:06
  • Why not just put both variants in one template and use `*ngIf`? – Dimanoid Apr 10 '19 at 21:06
  • Yes, I saw this link and yep it's about AOT in prod. It's some time since angular 5 so I've had a small hope that something changed in this subject. Yes, I could do it with ngIf or create abstract classes, and components for mobile / desktop to inherit from it to hold logic in one place + make seperate routing for mobile but It's quite ugly solution. – Adrian Sawicki Apr 10 '19 at 21:09

1 Answers1

1

The @Component declaration is processed statically with AOT complication and templateUrl cannot be provided based on a variable.

A way to handle this is to separate out your logic from the way the page is rendered. Any piece of UI that is displayed differently on mobile and desktop you can create separate component for. The main component or a shared base class or component should contain all logic.

<div>

  <p>Graph:</p>

  <graph-mobile *ngIf="mobile" [data]="data"></graph-mobile>

  <graph-desktop *ngIf="!mobile" [data]="data"></graph-desktop>

</div>
Noremac
  • 554
  • 2
  • 7
  • Yes, it is the most basic way to solve it but I'm looking for something smarter (if there even is a better way to solve it). Btw: The bad thing about it is that you have to copy logic to 2 typescript files. I'm thinking about abstract classes + something similar but more based on routing. – Adrian Sawicki Apr 10 '19 at 21:14
  • I updated the answer to make it more clear that logic should not be duplicated. Routing is fine. You can try to build your app routes dynamically or use activation guards (CanActivate) to possibly redirect users based on the mobile value. – Noremac Apr 10 '19 at 21:24